我尝试在一个协程中初始化三个集合,但只在第一个工作。只有当我在不同的协程中设置收集时,它才会工作。为什么?
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 }
}
}
}发布于 2021-02-06 03:13:37
StateFlow永远不会完成,因此收集它是一个无限的操作。这在the documentation of StateFlow中有解释。协程是连续的,所以如果您在StateFlow上调用collect,协程中调用之后的任何代码都不会被访问。
由于收集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() }
}https://stackoverflow.com/questions/66067121
复制相似问题