feroz_baig
07/26/2017, 8:11 AMfun main(args: Array<String>) = runBlocking {
val job = launch(CommonPool) {
var nextPrintTime = System.currentTimeMillis()
var i = 0
while (i < 10) { // computation loop
val currentTime = System.currentTimeMillis()
if (currentTime >= nextPrintTime) {
println("I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancel() // cancels the job
delay(1300L) // delay a bit to see if it was cancelled....
println("main: Now I can quit.")
}
Why is the job not cancelled after calling it explicitly?diesieben07
07/26/2017, 8:12 AMferoz_baig
07/26/2017, 8:13 AMfun main(args: Array<String>) = runBlocking<Unit> {
val job = launch(CommonPool) {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancel() // cancels the job
delay(1300L) // delay a bit to ensure it was cancelled indeed
println("main: Now I can quit.")
}
Well this suspendsdiesieben07
07/26/2017, 8:13 AMferoz_baig
07/26/2017, 8:14 AMjob.cancel()
diesieben07
07/26/2017, 8:15 AMferoz_baig
07/26/2017, 8:16 AMpilgr
07/26/2017, 8:25 AMrepeat
lambda
https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#cancellation-is-cooperativevoddan
07/26/2017, 8:55 AMdelay(0)
, but optimized for that scenario. Then it could be inserted into long-running jobs like abovekingsley
07/26/2017, 9:15 AMuhe
07/26/2017, 9:18 AMyield()
for this?pilgr
07/26/2017, 9:22 AMlaunch(CommonPool)
inside the repeat
. In this case I suppose after calling job.cancel()
coroutine won’t proceed after latest delay(500L)
. The drawback is frequent context switching.yield()
is a good catch! it’s mentioned as one of the ways to make computation cancellable but no examples
https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#making-computation-code-cancellablekingsley
07/26/2017, 9:35 AMyield
. For a moment, I thought that was only available to generateSequence