提问人:timjeric 提问时间:11/15/2023 更新时间:11/15/2023 访问量:17
在这种情况下,有没有更好的方法来组合ViewModel中的流程?
Is there a Better way of combining flows in ViewModels in this situation?
问:
我的 ui 状态 (TimerSetupState) 中有字段,可以通过 timerItemsFlow 和直接更新 _state 变量来更新。目前,我正在使用 onEach() 的 timerItemsFlow 并在 onEach() 中调用 _state.update()(updateState() 函数在内部调用 _state.update())。
private val timerItemsFlow = repository.getAllTimerItemsStream().onEach { timerItems -> updateState(timerItems) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList())
private val _state = MutableStateFlow(TimerSetupState())
val state = combine(_state, timerItemsFlow) { state, timerItems -> state }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), TimerSetupState())
如果我将 timerItemsFlow 发出时更新状态的逻辑放在 combine 块中,那么由 ui 事件(调用 _state.update() 函数)直接更新_state流的字段将被覆盖。我想知道是否有更好的方法可以保持订阅 timerItemsFlow,而无需与_state结合使用并忽略该值,或者只是我现在正在做的事情的更好方法。
如果您需要更多上下文:
主屏幕上的用户选择将在通知中 x 分钟后显示的数字。我不希望用户能够选择已选择但尚未触发通知的号码。
我也不希望用户能够在同一“通知”中两次选择相同的号码,因此当用户将号码添加到“TimeBlock”(屏幕底部的框)时,状态会更新,这些号码将变为“不可用”。
此外,当用户打开应用程序时,他不应该看到尚未触发通知的数字,这就是使用 timerItemsFlow 来更新它的原因。但是,当通知触发并且用户仍在主屏幕上时,他不必关闭并打开应用程序即可再次使用这些号码。这就是使用流而不是一次性读取函数的原因。
如果有帮助,该代码在 GitHub 上是公开的: https://github.com/TimJeric1/FunTimer
如果有人对 repo 中的代码有任何其他建议,请随时分享,我很高兴听到反馈。
答: 暂无答案
评论