invokeOnCompletion

open fun invokeOnCompletion(
    onCancelling: Boolean,
    invokeImmediately: Boolean,
    handler: CompletionHandler
): DisposableHandle
(source)

Overrides Job.invokeOnCompletion

Registers handler that is synchronously invoked once on cancellation or completion of this job. When job is already cancelling or complete, then the handler is immediately invoked with a job’s cancellation cause or null unless invokeImmediately is set to false. Otherwise, handler will be invoked once when this job is cancelled or complete.

Invocation of this handler on a transition to a transient cancelling state is controlled by onCancelling boolean parameter. The handler is invoked on invocation of cancel when job becomes cancelling if onCancelling parameter is set to true. However, when this Job is not backed by a coroutine, like CompletableDeferred or CancellableContinuation (both of which do not posses a cancelling state), then the value of onCancelling parameter is ignored.

The resulting DisposableHandle can be used to dispose the registration of this handler and release its memory if its invocation is no longer needed. There is no need to dispose the handler after completion of this job. The references to all the handlers are released when this job completes.

Installed handler should not throw any exceptions. If it does, they will get caught, wrapped into CompletionHandlerException, and rethrown, potentially causing crash of unrelated code.

Note: This function is a part of internal machinery that supports parent-child hierarchies and allows for implementation of suspending functions that wait on the Job’s state. This function should not be used in general application code. Implementations of CompletionHandler must be fast and lock-free.

Parameters

onCancelling - when true, then the handler is invoked as soon as this job transitions to cancelling state; when false then the handler is invoked only when it transitions to completed state.

invokeImmediately - when true and this job is already in the desired state (depending on onCancelling), then the handler is immediately and synchronously invoked and NonDisposableHandle is returned; when false then NonDisposableHandle is returned, but the handler is not invoked.

handler - the handler.