Kotlin/kotlinx.coroutines

Provide API for blocking call invocation on job completion and/or cancellation

Open

#728 opened on Oct 18, 2018

View on GitHub
 (3 comments) (1 reaction) (0 assignees)Kotlin (13,749 stars) (1,927 forks)batch import
designhelp wanteduse-case needed

Description

In Ktor, we have a use-case where a call to blocking API should be made when Job is being canceled with an additional requirement that Job should not complete until this blocking call is done. It can be generalized as "invoke blocking API on Job cancellation as part of job hierarchy".

Currently, it can be emulated with the following pattern:

val job = ...
launch(job) {
    try {
        suspendForever() // e.g. delay(Long.MAX_VALUE)
    } catch (e: CancellationException) {
        withContext(NonCancellable) { blockingCall() }
    }
}

Another solution is to use internal API: job.invokeOnCancellaion(onCancelling = true) { launch(job) { blockingCall() } }

If there is a demand (or compelling use-case) we can provide a much convenient way to plug blocking shutdown sequence into job hierarchy. In that API we can guarantee non-cancellability, well-behaving dispatcher (e.g. not Unconfined) and other goodies (e.g. suspending context, less resource consumption etc.).

Note: described primitive is not equivalent to

job.join()
blockingCall()

because job will completed before blockingCall is eve started.

Contributor guide