Issue
I have 2 stateFlow's in my viewModel. To collect them in fragment I have to launch coroutines 2 times as below:
lifecycleScope.launchWhenStarted {
stocksVM.quotes.collect {
if (it is Resource.Success) {
it.data?.let { list ->
quoteAdapter.submitData(list)
}
}
}
}
lifecycleScope.launchWhenStarted {
stocksVM.stockUpdate.collect {
log(it.data?.data.toString())
}
}
If I have more stateFlow's, I have to launch coroutines respectively. Is there a better way to handle multiple stateFlow's in my Fragment/Activity or wherever?
Solution
You will need different coroutines, since collect()
is a suspending function that suspends until your Flow
terminates.
For collecting multiple flows the currently recommended way is:
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
launch {
stocksVM.quotes.collect { ... }
}
launch {
stocksVM.stockUpdate.collect { ... }
}
}
}
Note that the problem with launchWhenStarted
is that while your newly emitted items will not be processed your producer will still run in the background.
I'd definitely give this a read, as it explains the current best-practices really well: https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda
Answered By - Róbert Nagy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.