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

nou*_*ian 4 android kotlin kotlin-coroutines kotlin-sharedflow

我试图使用sharedFlow将事件从UI传递到viewModel,这是我的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) {...}
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

这就是我发出动作的方式

private fun emitActions(action: Action) {
        lifecycleScope.launch {
        vm.actions.emit(action)
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

我在这里做错了什么吗?

nou*_*ian 5

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