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

Xitij

10/05/2020, 9:14 AM
Copy code
suspend 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🔦
t

tseisel

10/05/2020, 9:47 AM
Job.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.html
❤️ 1
j

Joris PZ

10/05/2020, 10:28 AM
You can wait for cancellation by
join()
-ing the job after calling
cancel()
, or do both in one go with
cancelAndJoin()
- this is a suspending function, and
isCompleted
will be true afterwards
❤️ 1
x

Xitij

10/05/2020, 12:06 PM
thank u soo sooo much for both of you
2 Views