我什么时候应该在 Fragment 生命周期中收集 SharedFlow 事件

Gök*_*ğcı 4 android kotlin-coroutines kotlin-sharedflow

SharedFlow我认为收集数据是可以的onViewCreated。但是当我替换片段 n 次然后我触发一些事件时SharedFlow,它会向我发出 n 次事件而不是一个事件。

为了解决这个问题,我将代码放入onCreate片段中。我找不到任何相关文档。我是否遗漏了一些东西,或者我应该继续收集SharedFlow片段onCreate

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
                            )
                        )
                    }
                }

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的SharedFlow定义ViewModel

private val _uiEffect = MutableSharedFlow<ViewEffectWrapper<LoginViewEffect>>(replay = 0)
val uiEffect: SharedFlow<ViewEffectWrapper<LoginViewEffect>> = _uiEffect
Run Code Online (Sandbox Code Playgroud)

che*_*e10 15

您当前没有使用viewLifecycleOwner,建议使用它,因为Fragments它与片段视图生命周期相关。这是推荐的方法

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        // ...
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.uiEffect.collect {
                    // do stuff here
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我也想读一读。这是一本很好的读物,值得为您提供帮助。

https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda