I’m collecting from a flow like so, as recommended...
# coroutines
a
I’m collecting from a flow like so, as recommended:
Copy code
lifecycleScope.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
.
Cancelling the outer scope when
flow.collect
returns seems to do the trick.
Copy code
suspend fun Lifecycle.runOnceOnLifecycle(
    state: Lifecycle.State,
    block: suspend CoroutineScope.() -> Unit
){
    coroutineScope {
        repeatOnLifecycle(state) {
            block()
            this@coroutineScope.cancel()
        }
    }
}
y
a
If I understand correctly,
whenStarted
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.
If
block
is collecting a flow, this will result in different behavior upstream.
m
Idk if there is any official way, but you can use a flag: .oncompleted {flag = true }