Hi! Why is this coroutine here that uses Thread.sl...
# coroutines
l
Hi! Why is this coroutine here that uses Thread.sleep() not cancelled?
Copy code
fun main() = runBlocking {

    val job = launch {
        repeat(5) { index ->
            println("operation number $index")
            ensureActive()
            Thread.sleep(100)
        }
    }
    delay(150)
    job.cancel()

}
all 5 lines are printed out, although actually only one should be printed out?
o
you never suspend, and
runBlocking
is a single thread, so
job.cancel()
never runs until it's already finished
t
add a yield
o
yes, either replace
ensureActive()
with
yield()
, or
delay
instead of
Thread.sleep
, or use
<http://Dispatcher.IO|Dispatcher.IO>
-- any of these will solve the issue, and may be appropriate depending on what you're actually doing
l
Ahh,
ensureActive
is a not a
supend
function, whereas
yield()
is one 🤔
💯 1
Thanks guys