Xitij
10/05/2020, 9:14 AMsuspend fun jobLifecycle () = coroutineScope {
val job = launch{
println("Working....")
delay(2000L)
println("Done !")
}
delay(1000L)
job.cancel()
// delay(1L) i have to do it to print correct value of job.isCompleted below
println("isCompleted: ${job.isCompleted}") // it is printing "false" but if i delay for some time after cancelling the job it prints "true".
}
is it my computer or it really takes some time to move job from cancelling to cancelled state where isCompleted becomes true after cancellation of job or is there something i'm missing out please review🔦tseisel
10/05/2020, 9:47 AMJob.cancel
is not a suspending function, which means that calling it will not immediately interrupt the associated coroutine.
AFAIK it will transition that coroutine to the Cancelling
state, which is not considered completed yet. There is a slight delay before that coroutine moves to the Cancelled
state ; your hardware is probably not in cause 😉
More on coroutine lifecycle: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.htmlJoris PZ
10/05/2020, 10:28 AMjoin()
-ing the job after calling cancel()
, or do both in one go with cancelAndJoin()
- this is a suspending function, and isCompleted
will be true afterwardsXitij
10/05/2020, 12:06 PM