Irsath Kareem
05/27/2025, 4:07 PMsomeGameRelatedFlow
.onCompletion { cause ->
println("onCompletion Called")
if(cause is CancellationException) {
try {
gameDao.invalidateJoinedRooms() // Suspending Call
} catch (e: CancellationException) {
CoroutineScope(Dispatchers.IO).async { //New CoroutineScope,because currentContext is already cancelled
launch {
delay(5000)
this@async.cancel()
}
gameDao.invalidateJoinedRooms() // Suspending Call
cancel()
}.await()
coroutineContext.ensureActive()
}
}
}
.stateIn(
scope, SharingStarted.WhileSubscribed(5000), null
)
My Assumption would be as follows,
When scope is cancelled, onCompletion's New CoroutineScope(IO) would do either of the following.....
1. At most 5000ms only it runs (OR)
2. if gameDao.invalidateJoinedRooms() finishes, onCompletion also finishes.
This pattern recommended?Zach Klippenstein (he/him) [MOD]
05/27/2025, 4:43 PMwithContext(NonCancellable)
would probably express your intent better in the catch
, and might be a bit more efficient too. And then I would probably use withTimeout
instead of implementing it manually.Irsath Kareem
05/28/2025, 12:52 AMwithContext
By the time withContext(NonCancellable)
is called, the current coroutineContext is already cancelled right, So withContext
is throwing CancellationException
right? (Before switching to NonCancellable
context)
Or it will switch to NonCancellable
context without regard of Cancelled CoroutineContext?Zach Klippenstein (he/him) [MOD]
05/28/2025, 3:32 PM