Kotlin Q & A

 

How do you handle coroutine cancellation nb in Kotlin?

Coroutine cancellation in Kotlin is an important aspect of coroutine management, allowing you to gracefully stop and clean up coroutines when they are no longer needed or when errors occur. Kotlin provides mechanisms for both cooperative and forced cancellation of coroutines.

To handle coroutine cancellation in Kotlin, you can use the cancel and cancelAndJoin functions provided by the Job interface, which is returned when a coroutine is launched. Additionally, you can handle cancellation using coroutine cancellation handlers such as invokeOnCompletion and withContext.

Here’s a basic example demonstrating coroutine cancellation in Kotlin:

kotlin

val job = CoroutineScope(Dispatchers.Default).launch {
 try {
 // Long-running coroutine code
 } finally {
 println("Coroutine cancelled")
 }
}

// Cancel the coroutine after a delay
delay(5000)
job.cancelAndJoin()

In this example, the launch coroutine is cancelled after a delay of 5000 milliseconds using the cancelAndJoin function. The try-finally block ensures that cleanup code is executed even if the coroutine is cancelled.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Android Engineer specializing in Kotlin with over 5 years of hands-on expertise. Proven record of delivering impactful solutions and driving app innovation.