How to Cancel Coroutine in Kotlin: Simple Guide
In Kotlin, you can cancel a coroutine by calling
cancel() on its Job. Coroutines support cooperative cancellation, so they must check for cancellation using functions like isActive or ensureActive() to stop execution cleanly.Syntax
To cancel a coroutine, you call cancel() on its Job or CoroutineScope. Inside the coroutine, you can check for cancellation using isActive or call ensureActive() to throw a CancellationException if cancelled.
job.cancel(): Requests cancellation of the coroutine.isActive: Boolean property to check if coroutine is still active.ensureActive(): ThrowsCancellationExceptionif coroutine is cancelled.
kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
while (isActive) {
println("Working...")
delay(500)
}
}
job.cancel()Example
This example shows how to start a coroutine, let it run for some time, then cancel it. The coroutine checks isActive to stop when cancelled.
kotlin
import kotlinx.coroutines.* fun main() = runBlocking { val job = launch { repeat(5) { i -> if (!isActive) return@launch println("Coroutine working: step $i") delay(300) } println("Coroutine completed") } delay(800) // Let coroutine run a bit println("Cancelling coroutine") job.cancel() // Cancel the coroutine job.join() // Wait for coroutine to finish println("Coroutine cancelled") }
Output
Coroutine working: step 0
Coroutine working: step 1
Coroutine working: step 2
Cancelling coroutine
Coroutine cancelled
Common Pitfalls
One common mistake is to cancel a coroutine but not check for cancellation inside it, so it keeps running. Another is ignoring CancellationException which is thrown when ensureActive() detects cancellation.
Always make your coroutine cooperative by checking isActive or calling ensureActive() periodically.
kotlin
import kotlinx.coroutines.* fun main() = runBlocking { val job = launch { // Wrong: No cancellation check, coroutine runs forever while (true) { println("Working without cancellation check") delay(300) } } delay(1000) println("Cancelling job") job.cancel() job.join() println("Job cancelled but coroutine may still run if not cooperative") }
Output
Working without cancellation check
Working without cancellation check
Working without cancellation check
Cancelling job
Job cancelled but coroutine may still run if not cooperative
Quick Reference
- Cancel coroutine:
job.cancel() - Check active:
isActiveproperty - Throw if cancelled:
ensureActive() - Wait for completion:
job.join()
Key Takeaways
Cancel a coroutine by calling cancel() on its Job or CoroutineScope.
Coroutines must cooperate by checking isActive or calling ensureActive() to stop on cancellation.
Always handle CancellationException properly to avoid unexpected crashes.
Use job.join() to wait for a coroutine to finish after cancellation.
Ignoring cancellation checks causes coroutines to keep running despite cancel requests.