Junior — Middle
How can you interrupt or cancel the execution of an asynchronous coroutine in your application?
sobes.tech AI
Answer from AI
In Kotlin, the mechanism for canceling or aborting an asynchronous coroutine is through the Job cancellation. To cancel a coroutine, you need to call the cancel() method on the corresponding Job.
Example:
val job = CoroutineScope(Dispatchers.Default).launch {
repeat(1000) { i ->
println("Working $i ...")
delay(500)
}
}
// Later, to cancel the execution:
job.cancel()
It is important that there are cancellation points inside the coroutine — for example, calls to suspend functions like delay(), which check the cancellation status and allow the coroutine to terminate properly.