android - 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)
}
}
第一次发射按预期发生,但随后它没有从视图模型发射/收集。
我在这里做错什么了吗?
解决方案
当我使用 collectLatest 而不是 collect 它按预期工作
推荐阅读
- python - python中的嵌套字典
- javascript - 从 NodeJS 中获取的子详细信息中遍历和构建 Tree
- firebase - Flutter Future:构建函数返回 null
- spring - 如何使用 spring-boot 为 Ldap 创建多个配置
- orm - 构建数据访问层
- flask - flask-admin:美化 json 字段
- javascript - 是否可以为 location.reload() 添加 javascript for/while 循环;
- html - 为什么网站渲染后会自动调用onclick函数-Flask?
- html - 兄弟按钮缩小和增长
- amazon-web-services - AWS Elasticache redis 突然变慢