Android项目中的SharedFlow未按预期工作



我试图使用sharedFlow将事件从UI传递到viewModel这是我的视图模型类

class MainActivityViewModel () : ViewModel() {
val actions = MutableSharedFlow<Action>()
private val _state = MutableStateFlow<State>(State.Idle)
val state: StateFlow<State> = _state
init {
viewModelScope.launch { handleIntents() }
}
suspend fun handleIntents() {
actions.collect {
when (it) {...}
}
}
}

这就是我发射的方式

private fun emitActions(action: Action) {
lifecycleScope.launch {
vm.actions.emit(action)
}
}

第一次发射按预期发生,但随后它没有从视图模型发射/收集。

我在这里做错什么了吗??

当我使用collectLatest()而不是collect()时,它按预期工作

collectLatest((而不是collect((隐藏问题

当您启动{collect((}时,collect将挂起启动代码块中的任何内容

所以如果你做

launch{
events.collect {
otherEvent.collect() //this will suspend the launched block indefinetly
} }

解决方案是将每个收集都封装在自己的启动{}代码块中,如果新事件被发出,collectLatest将取消挂起

您尝试过使用UnconfinedTestDispatcher()吗?这应该可以解决问题

最新更新