Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Coroutines

Kotlin Coroutines

A coroutine is a lightweight thread that can suspend and resume, addressing the complexity of asynchronous code and deeply nested callbacks.

Asynchronous code written with coroutines looks almost identical to synchronous code, but it does not block threads at runtime.


What Is a Coroutine

Traditional asynchronous programming relies on callbacks; nesting a few tasks creates "callback hell", and error handling is scattered.

Another approach is to start threads, but threads are scheduled by the OS, are expensive to create, and incur high context-switching costs when numerous.

Coroutines take a third path: they run on top of threads, with compiler-generated code handling suspension and resumption, so a single thread can run thousands of coroutines at once.

The key is that "suspending" is not "blocking": when a coroutine hits a long-running operation, it yields the thread so the thread can do other work, and the coroutine is resumed once the result is ready.

Coroutines are therefore ideal for scenarios like network requests, file I/O, and database access, where waiting time far exceeds computation time.

Coroutines became stable in Kotlin 1.3, with the API provided by the official library kotlinx-coroutines.


Your First Coroutine

The two most commonly used builders are runBlocking and launch.

runBlocking blocks the current thread until all coroutines inside it finish, and is normally used only in main functions and tests.

launch starts a coroutine without blocking the current thread and returns a Job object.

Example

import

kotlinx.coroutines.delay

import

kotlinx.coroutines.launch

import

kotlinx.coroutines.runBlocking

fun main

(

)

=

runBlocking

{

         

// Block the main thread until all inner coroutines finish

    println

(

"Start, thread: ${Thread.currentThread().name}"

)

    launch

{

                     

// Start a coroutine without blocking the following code

        delay

(

100

)

               

// Suspend for 100 ms; the thread can do other work meanwhile

        println

(

"Coroutine A finished"

)

   

}

    launch

{

        delay

(

50

)

        println

(

"Coroutine B finished"

)

   

}

    println

(

"main coroutine continues"

)

}

The example produces the following output:



开始,线程:main

main 协程继续执行

协程 B 完成

协程 A 完成

You can see "main coroutine continues" printed first, showing that launch did not block.

B waits only 50 ms while A waits 100 ms, so B finishes first.

Tip:runBlocking really blocks the thread, and using it in server-side business code slows down the whole thread pool, so it is only suitable as a "bridge" at the entry point or in tests. In business code you should use launch、async or coroutineScope。


suspend Functions

The suspend keyword marks a function that can suspend; it can only be called from a coroutine or another suspend function.

Sequence diagram of coroutine suspension and resumption: the main thread launches a coroutine, the thread is released after calling a suspending function, an IO thread makes the network request, the coroutine resumes when it returns, and the main thread continues executing

The compiler adds an extra parameter to a suspend function to pass the continuation, so it can remember where it suspended.

Example

import

kotlinx.coroutines.delay

import

kotlinx.coroutines.runBlocking

// suspend function: simulate a network request

suspend fun fetchSite

(

)

:

String

{

    delay

(

100

)

                   

// Suspend without occupying a thread

   

return

"www.runoob.com"

}

suspend fun printSite

(

)

{

    println

(

"Start fetching"

)

    val site

=

fetchSite

(

)

       

// Call a suspend function from within a suspend function

    println

(

"Site: $site"

)

}

fun main

(

)

=

runBlocking

{

    printSite

(

)

}

The example produces the following output:



开始获取

站点:www.runoob.com

If you put fetchSite() directly inside an ordinary function, the compiler reports an error saying it can only be called from a coroutine.

This is why many framework APIs are declared as suspend functions, automatically putting callers into a coroutine context.


Structured Concurrency and coroutineScope

Structured concurrency means a parent coroutine waits for all its children to finish before completing, and a child's failure also affects the parent.

The benefit is no "coroutine leaks": whoever starts a coroutine is responsible for waiting for it to finish.

coroutineScope creates a child scope and suspends until all its child coroutines complete.

Example

import

kotlinx.coroutines.coroutineScope

import

kotlinx.coroutines.delay

import

kotlinx.coroutines.launch

import

kotlinx.coroutines.runBlocking

suspend fun loadHomePage

(

)

=

coroutineScope

{

    launch

{

        delay

(

200

)

        println

(

"Module A loaded"

)

   

}

    launch

{

        delay

(

100

)

        println

(

"Module B loaded"

)

   

}

    println

(

"Waiting for all child coroutines..."

)

}

 

// This suspends until both child coroutines finish

fun main

(

)

=

runBlocking

{

    loadHomePage

(

)

    println

(

"Home page fully ready"

)

}

The example produces the following output:



等待所有子协程……

模块 B 加载完成

模块 A 加载完成

首页全部就绪

If you want one child's failure not to affect its siblings, use supervisorScope.

Builder Return Value Exception Behavior Typical scenario
runBlocking Lambda Return Value Exceptions propagate outward main functions, test entry points
launch Job Exceptions propagate upward and cancel the parent coroutine Parallel tasks that do not need a result
async Deferred Exceptions are deferred until await is called Parallel tasks that need a result
coroutineScope Lambda Return Value Any child failure fails the whole scope Concurrency inside a suspend function
supervisorScope Lambda Return Value Child failures do not affect each other One failure does not affect the others

Dispatchers (Schedulers)

A dispatcher decides which thread or thread pool a coroutine runs on; withContext lets you switch temporarily.

There are four commonly used dispatchers, chosen by task type: CPU-bound or blocking IO.

Dispatcher Thread Pool Applicable scenarios
Dispatchers.Default Number of CPU cores (at least 2) CPU-bound tasks such as sorting, parsing, and encryption
Dispatchers.IO Scales on demand, with a default cap of 64 File I/O, network requests, database access
Dispatchers.Main Main thread Updating the UI on Android, desktop Swing/JavaFX
Dispatchers.Unconfined Unrestricted; resumes on the caller's thread Rarely used, generally only in tests

Example

import

kotlinx.coroutines.Dispatchers

import

kotlinx.coroutines.runBlocking

import

kotlinx.coroutines.withContext

fun main

(

)

=

runBlocking

{

    println

(

"Main thread: ${Thread.currentThread().name}"

)

    withContext

(

Dispatchers.

Default

)

{

        println

(

"Is Default on the main thread: ${Thread.currentThread().name == "

main

"}"

)

   

}

    withContext

(

Dispatchers.

IO

)

{

        println

(

"Is IO on the main thread: ${Thread.currentThread().name == "

main

"}"

)

   

}

    println

(

"Still on at the end: ${Thread.currentThread().name}"

)

}

The example produces the following output:



主线程:main

Default 在主线程吗:false

IO 在主线程吗:false

结束时仍在:main

Tip:Dispatchers.Main requires an additional platform dependency. On Android it is kotlinx-coroutines-android, and on desktop Swing it is kotlinx-coroutines-swing, otherwise the runtime throws "Module with the Main dispatcher had failed to initialize".


Cancellation and Timeouts

Coroutine cancellation is cooperative: calling cancel() only sends a cancellation request, and the coroutine actually exits only at a suspension point.

Suspend functions in kotlinx.coroutines such as delay and yield check the cancellation state.

Example

import

kotlinx.coroutines.delay

import

kotlinx.coroutines.launch

import

kotlinx.coroutines.runBlocking

import

kotlinx.coroutines.withTimeoutOrNull

fun main

(

)

=

runBlocking

{

   

// Cancel a long-running coroutine

    val job

=

launch

{

        repeat

(

5

)

{

i

->

            delay

(

200

)

               

// Suspension points check whether cancellation has been requested

            println

(

"Download #$i..."

)

       

}

   

}

    delay

(

450

)

                       

// Let it run for a while first

    println

(

"Cancel task"

)

    job.

cancel

(

)

                     

// Send the cancellation request

    job.

join

(

)

                       

// Wait for cancellation to actually complete

    println

(

"Task stopped, isCancelled = ${job.isCancelled}"

)

   

// Timeout control

    val result

=

withTimeoutOrNull

(

300

)

{

        delay

(

1000

)

                   

// Give up if it takes more than 300 ms

       

"Download complete"

   

}

    println

(

"Timeout result: $result"

)

}

The example produces the following output:



第 0 次下载……

第 1 次下载……

取消任务

任务已停止,isCancelled = true

超时结果:null

withTimeout throws TimeoutCancellationException on timeout, while withTimeoutOrNull returns null.

If a coroutine is doing pure computation with no suspension points, cancellation has no effect; in that case you should call ensureActive() or check isActive yourself.

Example

import

kotlinx.coroutines.ensureActive

import

kotlinx.coroutines.launch

import

kotlinx.coroutines.runBlocking

fun main

(

)

=

runBlocking

{

    val job

=

launch

{

        var sum

=

0L

       

for

(

i in

1

..

1

_000_000_000

)

{

            sum

+=

i

           

if

(

i

%

10

_000_000

==

0

)

{

                ensureActive

(

)

       

// Check cancellation state explicitly

                println

(

"Computed up to $i"

)

           

}

       

}

   

}

    job.

cancel

(

)

                     

// Cancel immediately

    job.

join

(

)

    println

(

"Cancelled: ${job.isCancelled}"

)

}

The example produces the following output:



已取消:true


Concurrency with async and await

launch does not return a result; use async when you need concurrent evaluation, as it returns a Deferred。

Calling await() suspends until the result is ready, and the two async blocks run truly in parallel.

Example

import

kotlinx.coroutines.async

import

kotlinx.coroutines.delay

import

kotlinx.coroutines.runBlocking

import

kotlin.system.measureTimeMillis

// Simulate a time-consuming module

suspend fun loadModule

(

name

:

String

, cost

:

Long

)

:

String

{

    delay

(

cost

)

   

return

"$name loaded"

}

fun main

(

)

=

runBlocking

{

    val time

=

measureTimeMillis

{

        val a

=

async

{

loadModule

(

"Module A"

,

300

)

}

 

// Start executing immediately

        val b

=

async

{

loadModule

(

"Module B"

,

300

)

}

 

// Start executing immediately

        println

(

a.

await

(

)

)

                           

// Wait for A

        println

(

b.

await

(

)

)

                           

// Wait for B

   

}

   

// Sequential execution takes about 600 ms; parallel is noticeably faster

    println

(

"Parallel execution: ${time < 600}"

)

}

The example produces the following output:



模块 A 加载完成

模块 B 加载完成

是否并行执行:true

Note:async It only makes sense inside a coroutine scope. If you write it in a coroutineScope { async { ... } } global scope outside of that, you lose structured concurrency and no one handles the exceptions.


Introduction to Flow

Flow is the coroutine version of a stream, used to handle asynchronous data streams that produce multiple values in sequence.

It is much like Sequence in that both are lazy, except that every stage of a Flow can be a suspend function.

Flow became stable in kotlinx.coroutines 1.4; its builder is flow { } and elements are emitted with emit.

Example

import

kotlinx.coroutines.flow.collect

import

kotlinx.coroutines.flow.filter

import

kotlinx.coroutines.flow.flow

import

kotlinx.coroutines.flow.map

import

kotlinx.coroutines.flow.toList

import

kotlinx.coroutines.runBlocking

// Cold stream: each collector triggers a full execution

fun numberFlow

(

)

=

flow

{

   

for

(

i in

1

..

5

)

{

        emit

(

i

)

                     

// Emit elements one by one

   

}

}

fun main

(

)

=

runBlocking

{

   

// map and filter are intermediate operations and are not executed immediately

    val result

=

numberFlow

(

)

        .

map

{

it

10

}

             

// Multiply each element by 10

        .

filter

{

it

20

}

         

// Keep only values greater than 20

        .

toList

(

)

                   

// Terminal operation that triggers the whole flow

    println

(

result

)

   

// collect consumes elements one by one

    numberFlow

(

)

.

collect

{

value

->

        println

(

"Received: $value"

)

   

}

}

The example produces the following output:



[30, 40, 50]

收到:1

收到:2

收到:3

收到:4

收到:5

Flow also offers several common operators: flowOn changes the dispatcher of the upstream, catch captures upstream exceptions, and onEach performs a side effect on every emission.

Example

import

kotlinx.coroutines.Dispatchers

import

kotlinx.coroutines.flow.catch

import

kotlinx.coroutines.flow.flow

import

kotlinx.coroutines.flow.flowOn

import

kotlinx.coroutines.flow.toList

import

kotlinx.coroutines.runBlocking

fun riskyFlow

(

)

=

flow

{

    emit

(

"First item"

)

   

throw

IllegalStateException

(

"Data source disconnected"

)

}

.

catch

{

e

->

    emit

(

"Caught exception: ${e.message}"

)

   

// Fall back inside the flow

}

fun main

(

)

=

runBlocking

{

   

// flowOn makes emission run on the IO thread while collection stays on the main thread

    val list

=

riskyFlow

(

)

        .

flowOn

(

Dispatchers.

IO

)

        .

toList

(

)

    println

(

list

)

}

The example produces the following output:



[第一项, 捕获到异常:数据源断开]


Exception handling

Exception handling in coroutines is similar to ordinary code: you can wrap suspend calls directly in try/catch.

coroutineScope propagates a child coroutine's exception upward so the outer catch can handle it.

Example

import

kotlinx.coroutines.coroutineScope

import

kotlinx.coroutines.delay

import

kotlinx.coroutines.launch

import

kotlinx.coroutines.runBlocking

suspend fun loadData

(

)

:

String

{

    delay

(

100

)

   

throw

IllegalStateException

(

"Server returned 500"

)

}

fun main

(

)

=

runBlocking

{

   

// Approach 1: try/catch inside the coroutine

    launch

{

       

try

{

            loadData

(

)

       

}

catch

(

e

:

Exception

)

{

            println

(

"Caught internally: ${e.message}"

)

       

}

   

}

   

// Approach 2: coroutineScope throws the exception to the caller

   

try

{

        coroutineScope

{

            loadData

(

)

       

}

   

}

catch

(

e

:

Exception

)

{

        println

(

"Caught externally: ${e.message}"

)

   

}

}

The example produces the following output:



内部捕获:服务器返回 500

外层捕获:服务器返回 500

Exceptions from root coroutines (launched directly and not caught) can be handled uniformly with a CoroutineExceptionHandler.

Example

import

kotlinx.coroutines.CoroutineExceptionHandler

import

kotlinx.coroutines.launch

import

kotlinx.coroutines.runBlocking

fun main

(

)

=

runBlocking

{

   

// The handler only applies to root coroutines and must be declared on the scope

    val handler

=

CoroutineExceptionHandler

{

_, e

->

        println

(

"Handled globally: ${e.message}"

)

   

}

    val job

=

launch

(

handler

)

{

       

throw

RuntimeException

(

"Task failed"

)

   

}

    job.

join

(

)

    println

(

"Main flow continues"

)

}

The example produces the following output:



全局处理:任务失败

主流程继续

Note:Do not swallow CancellationException. When catching Exception you should first check whether it is a cancellation exception, otherwise a normal cancellation will be treated as an error.


Adding dependencies

Coroutines are not part of the Kotlin standard library, so you need to add kotlinx-coroutines-core separately.

The version must match the Kotlin compiler; Kotlin 2.2 recommends using 1.10.x.

Example

// File path: build.gradle.kts

plugins

{

    kotlin

(

"jvm"

)

version

"2.2.0"

}

dependencies

{

   

// Core library, required on all platforms

    implementation

(

"org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2"

)

   

// Needed on Android when using Dispatchers.Main

    implementation

(

"org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2"

)

   

// Coroutine test utilities runTest / TestDispatcher

    testImplementation

(

"org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2"

)

}

When using Maven, choose the artifact with the -jvm suffix for the JVM platform.

Example

   

org.jetbrains.kotlinx

   

kotlinx-coroutines-core-jvm

   

1.10.2


Common questions

The following questions come up most often when learning coroutines.

Suspend function should be called only from a coroutine

A suspend function is called from a regular function. Make the caller suspend too, or wrap it with runBlocking or launch.

Why is the coroutine still running after cancel

Cancellation is cooperative; a coroutine will not exit unless it stops at a suspension point. Add ensureActive() or yield() inside loops.

What is the difference between runBlocking and coroutineScope

runBlocking blocks the thread and is used at the outermost entry point; coroutineScope only suspends the coroutine without blocking the thread and is used inside suspend functions.

Why isn't the exception in launch printed

If an exception occurs in a non-root coroutine, it is propagated upward and cancels the parent coroutine. Either use try/catch inside it or add a CoroutineExceptionHandler to the root coroutine.

How to choose between Flow and Sequence

Use Sequence for pure, synchronous computation; use Flow when suspension is involved (network, IO).

Will Dispatchers.IO cause a thread explosion

No. Its default limit is 64 threads, which can be adjusted with the system property kotlinx.coroutines.io.parallelism.