Hi everyone, Whether this code is recommended or ...
# coroutines
i
Hi everyone, Whether this code is recommended or anti-pattern
Copy code
someGameRelatedFlow 
    .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?
z
withContext(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.
i
Thank you for your answer. But, need one small clarification about
withContext
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?
z
no, it won't throw