https://kotlinlang.org logo
Title
s

Shmuel Rosansky [G]

01/08/2020, 10:32 PM
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

octylFractal

01/08/2020, 10:34 PM
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

Shmuel Rosansky [G]

01/08/2020, 10:39 PM
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

octylFractal

01/08/2020, 10:40 PM
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

Shmuel Rosansky [G]

01/08/2020, 10:42 PM
right, but if by base context is UI then I generally won't be using withContext(UI) { .. } after making an IO call
o

octylFractal

01/08/2020, 10:42 PM
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

Shmuel Rosansky [G]

01/08/2020, 10:43 PM
ah, I see
looks like I'm using coroutineScope { }
o

octylFractal

01/08/2020, 10:45 PM
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

Shmuel Rosansky [G]

01/08/2020, 10:52 PM
Ok, thanks. I'll dig into this