Hi, `runInterruptible` allows the cancellation of ...
# coroutines
f
Hi,
runInterruptible
allows the cancellation of blocking operations that are sensitive to thread interrupts (https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-interruptible.html). However in the java ecosystem there are several blocking operations that are not sensitive to interrupts, such as some sockets methods (IINM). In those cases, sometimes there is an alternative way to cancel the blocking operation, other than by interrupts. For instance, on sockets we can cancel a pending operation by closing the socket (from a different thread). In this context 1. Is there anything similar to
runInterruptible
, where the cancelling action is not to send an interrupt but instead to perform a custom action, such as calling a
close
on some object? 2. If there isn't, we could eventually try to build one. For that we probably need to register an
invokeOnCompletion
that triggers on the
cancelling
state and not only on the
cancelled
state. This would allow us to perform an action when the coroutine transitions to
cancelling
. There is an
invokeOnCompletion
that allows that, however it is marked as
@InternalCoroutinesApi
. Is there any alternative public and stable API to do that, i.e., trigger a callback when a coroutine transitions into the
cancelling
state? Thanks.
e
I think you should be able to build something without resorting to internal APIs.
Copy code
coroutineScope {
    val r = async(<http://Dispatchers.IO|Dispatchers.IO>) { socket.read() }
    try {
        r.await()
    } catch (e: CancellationException) {
        socket.close()
        throw e
    }
}
f
This code takes advantage of the fact that the
r.await
will immediately throw
CancellationException
when
r
transitions into the
cancelling
state, before the
socket.read()
terminates, right? If so, seems a very interesting solution. Thanks.