Junior — Middle
How is stopping and pausing coroutine execution achieved in asynchronous applications?
sobes.tech AI
Answer from AI
In Kotlin, coroutines are managed using Job and CoroutineScope objects. To suspend and stop coroutines, the following mechanisms are used:
-
Suspension — coroutines can be suspended using the
suspendkeyword and functions that suspend themselves (e.g.,delay()). During suspension, the thread is not blocked, and the coroutine resumes later. -
Cancellation (stopping) — coroutines can be canceled by calling the
cancel()method on theirJob. Upon cancellation, the coroutine receives aCancellationExceptionand should terminate gracefully.
Example of canceling a coroutine:
val job = CoroutineScope(Dispatchers.Default).launch {
repeat(1000) { i ->
println("Working $i ...")
delay(500)
}
}
// Cancel the coroutine after 2 seconds
CoroutineScope(Dispatchers.Default).launch {
delay(2000)
job.cancel()
println("Coroutine canceled")
}
Thus, suspension is a natural part of coroutine operation, and stopping is achieved through cancellation via Job.