i was messing around with the `withTimeout` functi...
# coroutines
w
i was messing around with the
withTimeout
function and found that if I put a loop, it does not trigger the timeout cancellation exception but if I use a delay statement for the same amount of time, then it triggers the catch block. Could anyone explain why?
j
Because the loop is just a CPU spin. You either need to use runInterrupt or whatever it's called or check isActive. Cancelation is cooperative.
w
oh thats interesting, thanks!
are there any alternatives to the runBlocking or checking isActive? because the code that I am trying to run inside the withTimeout is legacy code that is written in java
z
runInterrupting will send a Java thread interrupt to the thread if the coroutine is cancelled while it’s blocked. If your legacy code doesn’t support interrupts, or provide its own cancellation api, I think you’re out of luck.