Another question about coroutines: in the tutorial...
# announcements
d
Another question about coroutines: in the tutorial there is an example where there process waits for coroutine to finish computation before it gets cancelled
Copy code
fun main(args: Array<String>) = runBlocking<Unit> {
    val startTime = System.currentTimeMillis()
    val job = launch {
        var nextPrintTime = startTime
        var i = 0
        while (i < 5) { // computation loop, just wastes CPU
            // print a message twice a second
            if (System.currentTimeMillis() >= nextPrintTime) {
                println("I'm sleeping ${i++} ...")
                nextPrintTime += 500L
            }
        }
    }
    delay(1300L) // delay a bit
    println("main: I'm tired of waiting!")
    job.cancelAndJoin() // cancels the job and waits for its completion
    println("main: Now I can quit.")
}
but the code below that
Copy code
fun main(args: Array<String>) = runBlocking<Unit> {
    val job = launch {
        try {
            repeat(1000) { i ->
                println("I'm sleeping $i ...")
                delay(500L)
            }
        } finally {
            println("I'm running finally")
        }
    }
    delay(1300L) // delay a bit
    println("main: I'm tired of waiting!")
    job.cancelAndJoin() // cancels the job and waits for its completion
    println("main: Now I can quit.")
}
is not being awaited to finish it’s job before cancellation
m
The difference is that
delay
handles cancellation. In the first example, there’s no
delay
within the
launch
, there’s just a
while
loop which runs continuously because its condition is updated only once a given time has updated. In the other examples, you use a
delay
statement, so the
cancel
applied to
job
has an immediate effect.
d
oh indeed, thank you, that explains it
🙂 1