invokeOnCancellation

abstract fun invokeOnCancellation(
    handler: CompletionHandler
): Unit
(source)

Registers handler that is synchronously invoked once on cancellation (both regular and exceptional) of this continuation. When the continuation is already cancelled, then the handler is immediately invoked with cancellation exception. Otherwise, the handler will be invoked once on cancellation if this continuation is cancelled.

Installed handler should not throw any exceptions. If it does, they will get caught, wrapped into CompletionHandlerException and processed as uncaught exception in the context of the current coroutine (see CoroutineExceptionHandler).

At most one handler can be installed on one continuation.

Note: Implementation of CompletionHandler must be fast, non-blocking, and thread-safe. This handler can be invoked concurrently with the surrounding code. There is no guarantee on the execution context in which the handler is invoked.