Search⌘ K
AI Features

Solution: Cancellation of a Job

Explore how to manage coroutine lifecycle by implementing job cancellation in Kotlin. Learn to create jobs, handle exceptions, and properly cancel coroutines with clear code explanations for effective coroutine management.

We'll cover the following...

Solution

suspend fun main(): Unit = coroutineScope {
   val job = Job()
   launch(job) {
       try {
           repeat(1_000) { i ->
               delay(200)
               println("i = $i")
           }
       } catch (e: CancellationException) {
           println(e)
           throw e
       }
   }
   delay(1500)
   job.cancelAndJoin()
   println("Canceled successfully")
}
Complete code for the solution

Explanation

Here is a line–by–line explanation of the code above:

...