Coroutine (Kotlin)

A coroutine is a lightweight, suspendable computation for writing asynchronous and concurrent code in a sequential style. Thousands can run on a few threads because suspending frees the thread instead of blocking it.

Kotlin

Coroutines let you write async code that reads top-to-bottom like normal code, without callbacks or futures. They run inside a CoroutineScope (started with launch for fire-and-forget or async for a result) and can suspend at suspend-function call sites, releasing the underlying thread until they resume.

Because suspension is cooperative and doesn't block a thread, you can have huge numbers of coroutines concurrently — far cheaper than threads. A Dispatcher decides which thread(s) they run on (Dispatchers.IO for blocking I/O, Default for CPU work, Main for UI).

Structured concurrency ties a coroutine's lifetime to its scope: cancel the scope and its children cancel too, which prevents leaks. Coroutines are the foundation of modern Kotlin async, with Flow built on top for streams of asynchronous values.

Syntax

runBlocking {
    launch { delay(100); println("world") }
    println("hello")
}

Examples

Kotlin — Prints 'started' then 'task done' because launch suspends without blocking.

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        delay(50)
        println("task done")
    }
    println("started")
    job.join()
}

Learn it in a lesson

See also

Back to the Dictionary