resume

abstract fun <R : T> resume(value: R, onCancellation: (cause: Throwable, value: R, context: CoroutineContext) -> Unit?)(source)

Resumes this continuation with the specified value, calling the specified onCancellation if and only if the value was not successfully used to resume the continuation.

The value can be rejected in two cases (in both of which onCancellation will be called):

  • Cancellation happened before the handler was resumed;

  • The continuation was resumed successfully (before cancellation), but the coroutine's job was cancelled before it had a chance to run in its dispatcher, and so the suspended function threw an exception instead of returning this value.

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

With this version of resume, it's possible to pass resources that can not simply be left for the garbage collector (like file handles, sockets, etc.) and need to be closed explicitly:

continuation.resume(resourceToResumeWith) { _, resourceToClose, _ ->
resourceToClose.close()
}

onCancellation accepts three arguments:

  • cause: Throwable is the exception with which the continuation was cancelled.

  • value is exactly the same as the value passed to resume itself. In the example above, resourceToResumeWith is exactly the same as resourceToClose; in particular, one could call resourceToResumeWith.close() in the lambda for the same effect. The reason to reference resourceToClose anyway is to avoid a memory allocation due to the lambda capturing the resourceToResumeWith reference.

  • context is the context of this continuation. Like with value, the reason this is available as a lambda parameter, even though it is always possible to call context from the lambda instead, is to allow lambdas to capture less of their environment.

A more complete example and further details are given in the documentation for the suspendCancellableCoroutine function.

Note: The onCancellation handler must be fast, non-blocking, and thread-safe. It can be invoked concurrently with the surrounding code. There is no guarantee on the execution context of its invocation.