我尝试在一个协程中初始化三个集合,但只在第一次工作。只有当我集合在不同的协程中它的工作时。为什么?
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 }
}
}
}
StateFlow永远不会完成,所以收集它是一个无限的操作。这在StateFlow的文档中有解释。协程是顺序的,所以如果你在StateFlow上调用collect
,协程中调用之后的任何代码都不会到达。
由于收集StateFlows和SharedFlows来更新UI是经常发生的事情,所以我使用这样的helper函数来使它更简洁:
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() }
}