在我看来,我不太明白一些事情。你能否向我解释为什么当我使用这个例子时,只有第一个集合对我有用。
lifecycleScope.launch {
viewModel.test1.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED).collect {
Log.i("Log_tag", it)
}
viewModel.test2.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED).collect {
Log.i("Log_tag", it)
}
}
或者如果我这样称呼他们:
lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
viewModel.test1.collect {
Log.i("Log_tag", it)
}
viewModel.test2.collect {
Log.i("Log_tag", it)
}
}
}
但是如果我在不同的协程中调用它们,那么它们都可以工作,如下所示:
lifecycleScope.launch {
viewModel.test1.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED).collect {
Log.i("Log_tag", it)
}
}
lifecycleScope.launch {
viewModel.test2.flowWithLifecycle(lifecycle, Lifecycle.State.STARTED).collect {
Log.i("Log_tag", it)
}
}
视图模型:
class ForecastViewModel : ViewModel() {
private val _test1 = MutableStateFlow("")
private val _test2 = MutableStateFlow("")
val test1 = _test1.asStateFlow()
val test2 = _test2.asStateFlow()
fun getTest() {
viewModelScope.launch {
_test1.value = "test1"
_test2.value = "test2"
}
}