Dias
09/10/2018, 11:56 PMfun 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
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 cancellationMartin Devillers
09/11/2018, 7:21 AMdelay
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.Dias
09/11/2018, 6:52 PM