Steffen Funke
03/29/2021, 11:36 AMaddRepeatingJob
API for safely consuming Flows from ViewModel (thanks @Manuel Vivo !): https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda
I am mostly observing multiple Flows from my ViewModel, e.g. one for the UI-State, and another one for One-Shot operations, like Toasts, Navigation, ...
Would it be safe to consume them like this, with launching sub-coroutines inside addRepeatingJob
? Or would it be better to have one viewLifecycleOwner.addRepeatingJob(Lifecycle.State.STARTED)
-Block for each observation?
viewLifecycleOwner.addRepeatingJob(Lifecycle.State.STARTED) {
launch {
viewModel.uiState.collect { uiState ->
// configure UI here
}
}
launch {
viewModel.events.collect { event ->
// react to one-shot events
}
}
}
Bernardo Macêdo
03/29/2021, 1:27 PMflowWithLifecycle
you will see this tip:
Tip: If multiple flows need to be collected using flowWithLifecycle, consider using the LifecycleOwner.addRepeatingJob API to collect from all of them using a different launch per flow instead. This will be more efficient as only one LifecycleObserver will be added to the lifecycle instead of one per flow.So I'm guessing you're doing the right thing there!
Steffen Funke
03/29/2021, 1:39 PM