首页 > 解决方案 > Android 项目中的 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) {...}
       }
   }
}

这就是我发出动作的方式

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

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

我在这里做错什么了吗?

标签: androidkotlinkotlin-coroutineskotlin-sharedflow

解决方案


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


推荐阅读