Also, when exactly are coroutines checked for canc...
# coroutines
m
Also, when exactly are coroutines checked for cancelation? Will a suspending function call check for cancelation before the function implementation is invoked? Will
withContext
check for cancelation upon before and/or after invoking
block
? Will
yield
check for cancelation immediately or on/after dispatch?
b
Will a suspending function call check for cancelation before the function implementation is invoked?
it's heavily depends on suspend fun implementation, by default suspend fun is not cancellable out of the box, so it needs to be designed to support cooperative cancellation (e.g. use built-in primitives or check for coroutine state).
Will 
withContext
 check for cancelation upon before and/or after invoking 
block
?
Should be both in general
Will 
yield
 check for cancelation immediately or on/after dispatch?
yield
will check it immediately, but will also resumed with exception if job was cancelled before re-dispatching. Also consider
ensureActive
for checking for cancellation in your non-cancellable code
m
Thank you for the clarification! I didn’t know about
ensureActive
. That seems helpful given that
suspend fun
don’t check for cancelation by default (unless it calls others that do). Do you happen to know a good open source example/library/app that properly manages various scopes & contexts and thus can serve as guidance?
l
withContext
since I don't recall which kotlinx.coroutines version does check for cancellation before and after invoking block using its given context (which, in case of
NonCancellable
, will be prevented).
u
I'd expect all suspension points to check for cancelation, at least on resume. There are not so many ways to cause suspension:
Suspend(Cancelable)Coroutine
,
yield
,
withContext
,
await
, and funs calling one of the above. what did i forget?
o
all suspension points can't check cancelation because suspend (Continuations) is a language feature, but coroutines are a library implemented on top of that e. g. sequences are suspend, but they do not cooperate with coroutines and do not dispatch, or handle cancelation. additionally, calling a suspend function will not result in a cancelation check
👍 1
another example is (until recently) Flow basic mechanisms did not check for cancelation
l
@octylFractal coroutines are not a library, kotlinx.coroutines is, and as of Kotlin 1.3, it brings cancellation support with
Job
. FYI, the "x" in kotlinx stands for extension.
o
alright, I suppose that's true, but it doesn't change what I said -- cancellation is not a concept in the stdlib, so not all suspension points check for it
"kotlinx.coroutines" is what brings cancellation to the table
l
That's true.
m
Interesting and makes sense. Thanks @octylFractal and @louiscad!