Android 项目中的 SharedFlow 未按预期工作
SharedFlow in Android project not working as expected
我试图使用 sharedFlow 将事件从 UI 传递到 viewModel
这是我的视图模型 class
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)
}
}
第一次发射如预期发生,但随后它不是来自视图模型的emitting/collecting。
我是不是做错了什么??
当我使用 collectLatest()
而不是 collect()
时,它按预期工作
我试图使用 sharedFlow 将事件从 UI 传递到 viewModel 这是我的视图模型 class
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)
}
}
第一次发射如预期发生,但随后它不是来自视图模型的emitting/collecting。
我是不是做错了什么??
当我使用 collectLatest()
而不是 collect()
时,它按预期工作