Doesn’t this depend on whether the blocking operation is interruptible or not? For example, runInterruptible()
won’t work with Socket
, but it should with SocketChannel
. Although, it is a matter of what we mean by “blocking”. As I understand, SocketChannel
uses non-blocking IO underneath, but it blocks the thread while waiting for IO.
But generally speaking: no, runInterruptible()
isn’t a bulletproof solution to running synchronous IO.
Some time ago I explored the topic of how to properly handle synchronous IO with coroutines, especially regarding cancellations. I think this topic isn’t very well documented in official docs (?). I found 3 possible solutions:
runInterruptible()
if we know IO is interruptible.- Create an utility that automatically closes a resource on cancellation. Something like: Cancel blocking function after timeout without 'select' - #2 by broot . This seems like the best solution in most cases, but it requires that we know a resource that is related to the IO operation.
- Run IO inside a child coroutine and make the parent not wait for it on cancellation. I didn’t find a way to do it properly, but I was able to achieve this with some hacking: Coroutine/Job that doesn't join its children when cancelled