如何解决我什么时候应该在 Fragment 生命周期中收集 SharedFlow 事件
我认为可以在 onViewCreated 上收集 SharedFlow 数据。但是当我替换片段 n 次然后向 SharedFlow 触发某个事件时,它会向我发出 n 次事件而不是一个事件。
我已经修复了如何将代码放在我的 Fragment 上的 onCreate 上。但我还没有找到任何关于它的文档。我是不是遗漏了什么,或者我应该继续在 Fragment 的 onCreate 中使用 SharedFlow 集合?
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launchWhenResumed {
viewmodel.uiEffect.collect {
when (it) {
is ViewEffectWrapper.PageEffect -> {
if (it.pageEvent is LoginViewEffect.OpenHomePage) {
startActivity(
Intent(
this@LoginFragment.context,HomeActivity::class.java
)
)
}
}
}
}
}
}
这是我在 viewmodel 上的 SharedFlow 定义
private val _uiEffect = MutableSharedFlow<ViewEffectWrapper<LoginViewEffect>>(replay = 0)
val uiEffect: SharedFlow<ViewEffectWrapper<LoginViewEffect>> = _uiEffect
解决方法
您当前未使用 viewLifecycleOwner
,建议将其用于 Fragments
,因为它与片段视图生命周期相关。这是推荐的方法
override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
// ...
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiEffect.collect {
// do stuff here
}
}
}
}
我也想读一读。这是一本很好的读物,值得为您提供帮助。
https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。