Kotlin/kotlinx.coroutines

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

オープン

#728 opened on 2018/10/18

 (3 件のコメント) (1 件のリアクション) (0 人の担当者)Kotlin (1,927 件のフォーク)batch import
designhelp wanteduse-case needed

Repository metrics

Stars
 (13,749 個のスター)
PR merge metrics
 (PR metrics pending)

説明

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.

コントリビューターガイド