Marek Kubiczek
08/23/2021, 3:46 PMviewLifecycleOwner.lifecycleScope.launch {
val result = someFlow.first()
doSomethingInUI(result)
}
where doSomethingInUI
is not a suspend
function.
What will happen if scope is destroyed/cancelled while there is ongoing operation someFlow.first()
(eg. database read). Is first()
cancellable? Will it exit the launch block gracefully or do I need to always call ensureActive()
before a call to non suspended function in such case?
The same stands for
someFlow.onEach {
doSomnethinginUI(it)
}.launchIn(viewLifecycleOwner.lifecycleScope)
Is there any guarantee onEach
won’t be called after scope is destroyed/cancelled?ephemient
08/23/2021, 7:04 PM.first()
is cancelable. you're not catching CancellationException
so it will leave scope naturally. .launchIn()
is equivalent to launch { .collect() }
, so it'll be sequenced with everything else on Main as long as you haven't switched to another dispatcher with withContext()
Marek Kubiczek
08/24/2021, 1:21 PMsomeFlow.onEach {
nonCancellableDelay()
}.onEach {
doSomnethinginUI(it)
}.launchIn(viewLifecycleOwner.lifecycleScope)
where the delay is non cancellable and defined as
suspend fun nonCancellableDelay() = suspendCoroutine<Unit> {
Handler(Looper.getMainLooper()).postDelayed(Runnable {
it.resume(Unit)
}, 2000)
}
I would expect the second onEach
shouldn’t be called in case scope has been destroyed meanwhile. But it’s not the case. Making me think that I can only be safe by calling ensureActive first which is counterintuitive.ephemient
08/24/2021, 4:04 PMephemient
08/24/2021, 4:05 PMMarek Kubiczek
08/24/2021, 4:08 PMephemient
08/24/2021, 4:10 PMephemient
08/25/2021, 1:37 AMlaunch(lifecycleScope) {
flow {
someFlow.collect {
nonCancellableDelay()
doSomnethinginUI(it)
emit(it)
}
}.collect()
}
ephemient
08/25/2021, 1:38 AMlaunch(lifecycleScope) {
nonCancellableDelay()
doSomethingInUi(it)
}
has the same behavior: if there's an actual suspension it'll throw CancellationException, but otherwise it just keeps runningephemient
08/25/2021, 1:42 AMMarek Kubiczek
08/26/2021, 6:08 AM