Coroutine: how to get notification when job is canceled?

I have this simple example of coroutine:

   val job = launch{
        delay(2000)
        println("done")
    }
    job.cancel()

The “done” is not printed as expected.
But how can I be notified when coroutine gets canceled (either directly or from its parent job)? Can I assign cancellation notification callback, or override some function to achieve it? Something like

job.runOnCanceled{ println("canceled") }

I want to run some cleanup code in case when coroutine is finished either normally (reaching end of async{} block) or when its canceled.

Thanks

1 Like

Take a look to:

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/invoke-on-completion.html

This solution has some limitations, alternatively you can use:

fun Job.runOnCanceled(context: CoroutineContext = DefaultDispatcher, handler: suspend (Job) -> Unit) {
    val job = this
    launch(context) {
        job.join()
        if (job.isCancelled)
            handler(job)
    }
}
2 Likes

You can use this:

CoroutineExceptionHandler

1 Like