Vivek Sharma
02/02/2021, 5:33 PMjean
02/03/2021, 6:54 AMlifeCycleScope
and viewModelScope
will take take of unregistering when necessary for you : https://developer.android.com/topic/libraries/architecture/coroutines#lifecycle-awareOrhan Tozan
02/03/2021, 2:34 PMNote: Usingfunctions from the Lifecycle Kotlin extensions to collect a flow from the UI layer is not always safe. When the view goes to the background, the coroutine suspends, leaving the underlying producer active and potentially emitting values that the view doesn't consume. This behavior could waste CPU and memory resources.launchWhen()
*`StateFlow`*s are safe to collect using theA way to combat this is always have a backed shared flow that collects while subscribed.functions since they're scoped to *`ViewModel`*s, making them remain in memory when thelaunchWhen()
goes to the background, and they do lightweight work by just notifying theView
about UI states. However, the problem might come with other producers that do more intensive work.View
jean
02/03/2021, 2:50 PMOrhan Tozan
02/03/2021, 2:52 PMval users: Flow<List<User>> = observeUsers()
its
val users: Flow<List<User>> = observeUsers()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList())
Vivek Sharma
02/03/2021, 3:03 PMOrhan Tozan
02/03/2021, 3:05 PMVivek Sharma
02/03/2021, 3:09 PMJohn O'Reilly
02/03/2021, 3:10 PMjean
02/03/2021, 3:31 PMSharingStarted
property on a state/shared flow declared like this val state = Mutable[State/Shared]Flow(initialValue)
? I see the doc says
the problem might come with other producers that do more intensive workwhat is intensive enough and does it mean it should be changed to a backed shared flow instead?
Vivek Sharma
02/03/2021, 3:33 PMOrhan Tozan
02/03/2021, 3:37 PMjean
02/03/2021, 3:39 PM