https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

voddan

02/26/2019, 2:06 PM
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

louiscad

02/26/2019, 2:17 PM
Blocking code does not support cancellation
2
g

gildor

02/26/2019, 2:53 PM
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

sitepodmatt

02/26/2019, 4:13 PM
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

louiscad

02/26/2019, 4:51 PM
You can also use
yield()
if the operation is actually a sum or loop of smaller I/O operations.
v

voddan

02/28/2019, 4:04 PM
Is there a safe way to abort the whole OS thread when I need to cancel the blocking operation?
g

gildor

02/28/2019, 4:30 PM
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

voddan

03/01/2019, 3:16 PM
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.
3 Views