StateFlow 在一个协程中进行收集

MXF*_*MXF 1 android kotlin kotlin-coroutines kotlin-stateflow

我尝试在一个协程中初始化三个收集,但仅第一个起作用。仅当我设置在不同的协程中收集其工作时。为什么?

  lifecycleScope.launch {
            launch {
                homeViewModel.dateStateFlow().collect { date ->
                    date?.let { calendar.text = date.toStringForView() }
                }
            }
            launch {
                homeViewModel.toStateFlow().collect { to ->
                    to?.let { cityTo.text = to.name }
                }
            }
            launch {
                homeViewModel.fromStateFlow().collect { from ->
                    from?.let { cityFrom.text = from.name }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

Ten*_*r04 5

StateFlow 永远不会完成,因此收集它是一个无限的操作。StateFlow 的文档对此进行了解释。协程是顺序的,因此如果您调用collectStateFlow,则协程中该调用之后的任何代码都不会被访问。

由于收集 StateFlows 和 SharedFlows 来更新 UI 是很常见的情况,因此我使用这样的辅助函数来使其更加简洁:

fun <T> LifecycleOwner.collectWhenStarted(flow: Flow<T>, firstTimeDelay: Long = 0L, action: suspend (value: T) -> Unit) {
    lifecycleScope.launch {
        delay(firstTimeDelay)
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            flow.collect(action)
        }
    }
}

// Usage:

collectWhenStarted(homeViewModel.dateStateFlow()) { date ->
    date?.let { calendar.text = date.toStringForView() }
}

Run Code Online (Sandbox Code Playgroud)