Alexander Maryanovsky
03/24/2022, 7:22 PMlifecycleScope.launch{
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
flow.collect{
...
}
}
}
I would like the collection, and the entire coroutine to stop when the flow completes. But repeatOnLifecycle
never returns, even after collect
returns, and if the activity is stopped and restarted, collection is launched again.
It seems I need runOnceOnLifecycle
.Alexander Maryanovsky
03/24/2022, 7:28 PMflow.collect
returns seems to do the trick.Alexander Maryanovsky
03/24/2022, 7:37 PMsuspend fun Lifecycle.runOnceOnLifecycle(
state: Lifecycle.State,
block: suspend CoroutineScope.() -> Unit
){
coroutineScope {
repeatOnLifecycle(state) {
block()
this@coroutineScope.cancel()
}
}
}
yschimke
03/24/2022, 9:43 PMAlexander Maryanovsky
03/25/2022, 4:20 AMwhenStarted
is not the same. repeatOnLifecycle(STARTED)
will cancel the coroutine running the block when the state is below started and start it again when the state is again started.
whenStarted
, on the other hand, will merely suspend the block.Alexander Maryanovsky
03/25/2022, 4:21 AMblock
is collecting a flow, this will result in different behavior upstream.myanmarking
03/25/2022, 10:50 PM