Does a suspend function check for the coroutine to...
# coroutines
s
Does a suspend function check for the coroutine to be active when the function resume and the coroutine is continued? ie, say you have a long running io call and during that time the coroutine job is canceled. When the io call completes will the coroutine resume or stop? I know that the suspend call will check for isActive before running the suspend block, but I can't find a definitive answer if it will resume without checking isActive. Thanks!
o
the
suspend
language feature itself does not know about cancellation, that's strictly a concept from the coroutines library. so it does not check for cancellation. many (but not all) functions provided by the coroutines library do check for cancellation, and the docs will say if they do or not
also, to be clear, usually a "long running IO call" is blocking, and therefore suspend mechanics do not come in to play at all.
s
yeah, correct. It's a network call that's being run on the IO context
ok, thanks this settles it then
is best practice to check for isActive when resuming after the network code?
o
as I said, some of the coroutines library provided functions already check that;
withContext
is one of them: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-context.html
Note that the result of withContext invocation is dispatched into the original context in a cancellable way, which means that if the original coroutineContext, in which withContext was invoked, is cancelled by the time its dispatcher starts to execute the code, it discards the result of withContext and throws CancellationException.
s
right, but if by base context is UI then I generally won't be using withContext(UI) { .. } after making an IO call
o
right, but did you do
withContext(IO)
?
the paragraph above describes the return path from
withContext
, in short
withContext
checks for cancellation before it returns
s
ah, I see
looks like I'm using coroutineScope { }
o
that doesn't change contexts though?
regardless, https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html
The method may throw a CancellationException if the current job was cancelled externally
s
Ok, thanks. I'll dig into this