Chapter 13. Coroutines and Structured Concurrency

One of Kotlin’s most popular features is its support for coroutines, which allow developers to write concurrent code as though it was synchronous. That support makes it much easier to write concurrent code that employs coroutines than using other techniques, like callback methods or reactive streams.

Note that the key word in that sentence is easier, rather than easy. Managing concurrency is always a challenge, especially when you try to coordinate multiple separate activities, handle cancellations and exceptions, and more.

This chapter discusses the issues related to Kotlin coroutines. These issues include working with coroutine scope and coroutine context, selecting the proper coroutine builder and dispatchers, and coordinating their behavior.

The idea behind coroutines is that they can be suspended and resumed. By marking a function with the suspend keyword, you’re telling the system that it can put the function on hold temporarily, and resume it on another thread later, all without having to write complex multithreading code yourself.

13.1 Choosing Coroutine Builders

Problem

You need to select the right function to create a coroutine.

Solution

Decide between the available builder functions.

Discussion

To create a new coroutine, you use one of the available builder functions: runBlocking, launch, or async. The first, runBlocking, is a top-level function, while launch and async are extension functions on CoroutineScope ...

Get Kotlin Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.