what would be a recommended way of registering a c...
# coroutines
m
what would be a recommended way of registering a callback for the scope cancellation (or all children)? Would the empty
callbackFlow
with
awaitClose
work here?
Copy code
fun CoroutineScope.onCancel(action: () -> Unit) {
        callbackFlow<Unit> { 
            awaitClose(action)
        }.launchIn(this)
    }
j
I think it would be more correct to access the
Job
from the scope's context:
Copy code
fun CoroutineScope.onCancel(action: () -> Unit) {
    coroutineContext.job.invokeOnCompletion { ex ->
        if (ex is CancellationException) {
            // do stuff
        }
    }
}
m
indeed it looks better, thanks!
j
There is an overload of
invokeOnCompletion
that you could use, but I'm not very familiar with it, so please read the docs 😉
🙏 1
Also, it might be important to note that not all `CoroutineScope`s have a
Job
in their contexts, in which case
coroutineContext.job
will fail. You can use
coroutineContext[Job]
instead if you want to get a nullable
Job?
instead and deal with it. If there is no
Job
, there is also no structurred concurrency, so I guess your use case only makes sense on scopes with a
Job
, but still good to know
m
yeah, I was wondering how the scope construction might impact that code, thanks for pointing that out
👍 1