Challenge: Cancellation of a Job

Solve a challenge regarding the cancellation of a coroutine.

We'll cover the following

Problem

When a job is canceled, it changes its state to “Cancelling.” Then, at the first suspension point, a CancellationException is thrown. Write a code that will catch this exception using try and catch and use the job factory function to cancel all the coroutines:

  • In the try block, print the value of i.

  • In the catch block, print the exception.

  • After try and catch, cancel coroutines using the job factory function, and then print “Canceled successfully.”

Note: Adjust the delay in such a way that we get our desired output.

Restriction

The output will be available in the terminal.

Output

i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
kotlinx.coroutines.JobCancellationException: Job was cancelled; ......
Canceled successfully

Get hands-on with 1200+ tech skills courses.