Sobes.tech
Junior — Middle

Explain the principle of coroutines in Kotlin and their main advantages.

sobes.tech AI

Answer from AI

Kotlin coroutines are lightweight threads that allow writing asynchronous, non-blocking code in a sequential style. They operate based on the concept of suspension and resumption of function execution without blocking the main thread.

Main advantages:

  • Simplifies writing asynchronous code without callbacks.
  • Lightweight compared to OS threads.
  • Easy to manage cancellation and timeouts.

Example of using a coroutine:

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(1000L)
        println("Hello from coroutine!")
    }
    println("Hello from main")
}

Here, launch starts a coroutine that suspends for 1 second without blocking the main thread.