A study note based on Kotlin Coroutine Guide. kotlinx.coroutines is a library for coroutines. Add kotlinx-coroutines-core to use it in project.

1 Basics

You launch a coroutine with the launch coroutine builder in a CoroutineScope.

delay is non-blocking. You can run it in a blocking mode using runBlocking { delay(2000L)}. Use join to wait in a non-blocking way.

Everyt coroutine builder, including runBlocking, adds an instance of CoroutineScope to the scope of its code block. The outer coroutine doesn’t complete until all the coroutine lauched inside it complete. Following is an example:

import kotlinx.coroutines.*

fun main() = runBlocking { // this: CoroutineScope
    launch { // launch a new coroutine in the scope of runBlocking

You can create a coroutine scope using the coroutineScope builder. It is a suspending function.

The suspend modify defines a suspending function that can be used in a coroutine like a regular function. A suspending function can call other suspending functions such as delay.

2 Cancellation and Concurrency

All suspending functions are cooperative and cancellable. They check for cancellation and throw CancellationException when cancelled. You can check isActive or use yield to cooperate.

The code in the coroutine, just like in the regular code, is sequential by default. Use async that runs a suspending function asynchronously. It can start in a lazy mode.

Use coroutineScope to run async code in a structured concurrency mode.

3 Context and Dispatcher

The coroutine context is a set of various elements including Job.

The coroutine dispatcher can confine coroutine execution to a specific thread, dispatch it to a thread pool, or let it run unconfined. All coroutine builders like launch and async accept an optional CoroutineContext parameter that can be used to explicitly specify the dispatcher for the new coroutine and other context elements.

4 Advance Topics

The Kotlin coroutine supports asynchronous flow, channels, supervision, shared mutable state and concurrency.