Hello! I have a typical task of wrapping blocking ...
# coroutines
v
Hello! I have a typical task of wrapping blocking IO calls into coroutines. Please point me to a working code example of that which supports job cancelation. Thank you
l
Blocking code does not support cancellation
2
g
Only if this blocking code has some loop (like reading/writing to IO stream) or just a few steps, in this case you can check isActive property of coroutine to check cancellation state
👍 1
s
Do you bother using isActive? I see in many of the jetbrains example they just let it hit the next suspending function and that throw cancellationexception and is ate the same. so they seem to use while(true) vs while(isActive)
obviously if no suspending function within the loop such fibanacci calc then you'd have to check isActive
l
You can also use
yield()
if the operation is actually a sum or loop of smaller I/O operations.
v
Is there a safe way to abort the whole OS thread when I need to cancel the blocking operation?
g
Yes, you can use Thread.interrupt(), but it's not a part of coroutines API (you need access to thread) and even with interrupt blocking code should support it (for example like Thread.sleep supports it, but it's not really widely supported API)
And if you can rewrite some blocking code to support thread interruption imo would be better rewrite it to support cancellation using coroutines
JVM doesn't support thread stopping anymore, it's not safe operation
v
I see, thank you! I wish this was mentioned in the docs since I guess it is a common wish to use old blocking api with coroutines.