What’s currently the best way to check for cancell...
# coroutines
p
What’s currently the best way to check for cancellation inside a suspend fun ?
coroutineScope { ensureActive() }
?
e
no need for a temporary scope, `currentCoroutineContext().isActive()`/`.ensureActive()` will work
j
Note that this will not work in contexts where you don't have a job. For instance in
suspend fun main
,
isActive
will be false. It might be safer to use
isActive
on a temporary scope (with job) if you don't control the calling context, and you want the "not cancelled" semantics
h
Or use
suspend fun main() = coroutineScope {
p
I think I’ll just wrap the whole suspend fun in
coroutineScope
— it just feels higher-level API and if context doesn’t have a job it will create one so I’ll be sure to call
ensureActive
in a scope with a job. In fact thinking of it I don’t know why every suspend fun does not get an implicit CoroutineScope with Job as a receiver by compiler magic but that’s another topic
e
because not all suspend funs are for kotlinx.coroutines