Sobes.tech
Junior — Middle

Could you explain the principle of interrupts in coroutines and how they interact with execution threads?

sobes.tech AI

Answer from AI

In Kotlin, coroutines are lightweight threads that allow writing asynchronous code sequentially. Coroutine cancellations (e.g., calling cancel) work through the Cooperative Cancellation mechanism, meaning the coroutine itself must check whether it has been canceled and terminate properly.

Working principle:

  • A coroutine is launched in a specific context and thread (Dispatcher).
  • When cancel() is called on the coroutine's Job, it receives a cancellation signal.
  • The coroutine must periodically check its state (e.g., via isActive or by calling suspend functions that check for cancellation).
  • If the coroutine does not check for cancellation, it will continue to work despite the cancel.

Interaction with threads:

  • Coroutines can switch between threads thanks to dispatchers (Dispatchers.IO, Dispatchers.Default, etc.).
  • Canceling a coroutine does not interrupt the thread, it only stops the execution of the coroutine itself.
  • Threads can run multiple coroutines sequentially (cooperative multitasking).

Example of coroutine cancellation:

val job = CoroutineScope(Dispatchers.Default).launch {
    repeat(1000) { i ->
        if (!isActive) return@launch // check for cancellation
        println("Working $i ...")
        delay(500)
    }
}

// Cancel after 1 second
delay(1000)
job.cancel()
Could you explain the principle of interrupts in… - sobes.tech