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.
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.
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.
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
.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.
Job.invokeOnCompletion(onCancelling = true) { /* callback */ }
, but this is internal API.This seems to be the most straightforward option, but using non-stable API is unacceptable in many scenarios.
It looks non-idiomatic, but it should work.
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.