Description
Use case
runInterruptible
allows one to run blocking Java code and interrupt it when the coroutine it's running in gets cancelled. Internally, this is implemented by reacting to notifications about the job entering the cancelling state.
There is no public API to subscribe to these notifications, but this pattern is occasionally useful outside of runInterruptible
.
- Some blocking calls can't be interrupted and require calling a special function to stop them. For example, Java sockets: https://stackoverflow.com/questions/2804797/java-stop-server-thread
- Non-Java APIs: Support for
runInterruptible
in Kotlin/Native (POSIX) targets #3563
In general, the use case is to do the same thing as runInterruptible
, but for the general problem of stopping some computations when cancellation requests arrive.
Shape of the API
Unclear. Maybe nothing should be added and we just need to document this use case better.
Workarounds
It's possible to get this functionality today, without any special API.
- We already have
Job.invokeOnCompletion(onCancelling = true) { /* callback */ }
, but this is internal API.
launch {
process.run()
}.invokeOnCompletion(onCancelling = true) {
process.stop()
}
This seems to be the most straightforward option, but using non-stable API is unacceptable in many scenarios.
- One can also write this using a low-level API:
suspendCancellableCoroutine { cont ->
cont.invokeOnCancellation {
process.stop()
}
process.run()
cont.resumeWith(Result.success(Unit))
}
It looks non-idiomatic, but it should work.
- It's possible to spawn another child for the sole purpose of sending asynchronous cancellation notifications.
launch {
launch { awaitCancellation() }.invokeOnCompletion {
process.stop()
}
process.run()
}
Note 1: this won't work in a single-threaded dispatcher.
Note 2: the only way for this coroutine to properly complete is to cancel. Otherwise, awaitCancellation
will be stuck forever.