Provide API for blocking call invocation on job completion and/or cancellation
#728 创建于 2018年10月18日
仓库指标
- 星标
- (13,749 个星标)
- PR 合并指标
- (PR 指标待抓取)
描述
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.