Skip to Main Content
Kotlin Cookbook
book

Kotlin Cookbook

by Ken Kousen
November 2019
Intermediate to advanced content levelIntermediate to advanced
254 pages
4h 55m
English
O'Reilly Media, Inc.
Content preview from Kotlin Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Functional Kotlin

Functional Kotlin

Mario Arias, Rivu Chakraborty
Kotlin Programming Cookbook

Kotlin Programming Cookbook

Aanand Shekhar Roy, Rashi Karanpuria
Functional Programming in Kotlin

Functional Programming in Kotlin

Runar Bjarnason, Paul Chiusano, Marco Vermeulen
Learning Concurrency in Kotlin

Learning Concurrency in Kotlin

Miguel Angel Castiblanco Torres

Publisher Resources

ISBN: 9781492046660Errata PageSupplemental Content