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

Lukas Lechner

08/10/2020, 8:12 AM
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

octylFractal

08/10/2020, 8:15 AM
you never suspend, and
runBlocking
is a single thread, so
job.cancel()
never runs until it's already finished
t

Tijl

08/10/2020, 8:16 AM
add a yield
o

octylFractal

08/10/2020, 8:17 AM
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

Lukas Lechner

08/10/2020, 8:19 AM
Ahh,
ensureActive
is a not a
supend
function, whereas
yield()
is one 🤔
💯 1
Thanks guys
4 Views