https://kotlinlang.org logo
Title
a

Andrea Giuliano

09/24/2020, 5:09 PM
Hi guys, I was playing with
withTimeout
function and I’ve noticed that if the block inside is not a suspending function, withTimeout simply does nothing. Is that the expected behaviour? I know from the spec it’s stated that the block is a suspending block. However I was expecting at least some error or warning if the block is not suspending. Anything I’m missing here?
s

streetsofboston

09/24/2020, 5:10 PM
withTimeout (or any cancellation of a coroutine) can only cancel a currently suspending function. It cannot cancel a blocking function.
a

Andrea Giuliano

09/24/2020, 5:12 PM
yeah I got that and it makes sense. Problem is I believe it’s very error prone. I could figure this out thanks to unit tests since I was expecting a compilation error saying that the block is not suspending
s

streetsofboston

09/24/2020, 5:40 PM
The compiler wouldn't know that.... Blocking code is not marked as such... There is a lint warning for when you call code that throws an IOException in a Coroutine for which it is not immediately clear that its dispatcher is Dispatchers.IO.... often this warning is wrong and not very useful...
l

louiscad

09/25/2020, 7:34 AM
You can use
withTimeout
+
runInterruptible
if the blocking code is interruptible though.
a

Andrea Giuliano

09/25/2020, 7:35 AM
that’s super @louiscad thanks for sharing