Careeroza
Cancelling a Coroutine
cancel and cancelAndJoin
Call job.cancel() to stop a coroutine. Cancellation is delivered as a CancellationException thrown at the next suspension point (delay, yield, withContext, a channel call...).
Example
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
repeat(10) { i ->
println("Syncing chunk $i")
delay(100)
}
}
delay(250)
println("User pressed Cancel")
job.cancelAndJoin()
println("Sync stopped. Cancelled = ${job.isCancelled}")
}Output
Syncing chunk 0 Syncing chunk 1 Syncing chunk 2 User pressed Cancel Sync stopped. Cancelled = true
Where It Comes From
- Screen closed:
viewModelScope/lifecycleScopecancels automatically. - User action: you keep the
Joband callcancel()(e.g. a new search replaces the old one). - Timeout:
withTimeoutcancels the block when time runs out. - Failure: a failing sibling in
coroutineScope.