Sobes.tech
Junior — Middle

How can you cancel a task launched via Kotlin Coroutine?

sobes.tech AI

Answer from AI

To cancel a task launched via Kotlin Coroutine, the cancellation mechanism through Job is used.

When you launch a coroutine, it returns a Job object, which can be used for cancellation:

val job = CoroutineScope(Dispatchers.Default).launch {
    // Long operation
    for (i in 1..1000) {
        if (!isActive) return@launch // check for cancellation
        println("Iteration $i")
        delay(100)
    }
}

// Later, to cancel the task:
job.cancel()

It is important to periodically check the isActive state inside the coroutine or use functions that support cancellation (such as delay) so that the coroutine can terminate correctly upon cancellation.

You can also use withTimeout or withTimeoutOrNull for automatic cancellation after a timeout.