0% found this document useful (0 votes)
19 views

Coroutines 1

Uploaded by

Alex Trujillo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Coroutines 1

Uploaded by

Alex Trujillo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Kotlin Coroutines

Deep Dive

Marcin Moskała
This book is for sale at http://leanpub.com/coroutines

This version was published on 2022-04-01

ISBN 978-83-963958-1-8

This is a Leanpub book. Leanpub empowers authors and publishers


with the Lean Publishing process. Lean Publishing is the act of
publishing an in-progress ebook using lightweight tools and many
iterations to get reader feedback, pivot until you have the right book
and build traction once you do.

© 2021 - 2022 Marcin Moskała


Tweet This Book!
Please help Marcin Moskała by spreading the word about this book
on Twitter!
The suggested tweet for this book is:
I just bought Kotlin Coroutines by Marcin Moskała
The suggested hashtag for this book is #KotlinCoroutines.
Find out what other people are saying about the book by clicking on
this link to search for this hashtag on Twitter:
#KotlinCoroutines
For my beloved wife, Maja.
Contents

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 1

Part 1: Understanding Kotlin Coroutines . . . . . . . . . . . 7


Why Kotlin Coroutines? . . . . . . . . . . . . . . . . . . . 8
Sequence builder . . . . . . . . . . . . . . . . . . . . . . . 20
How does suspension work? . . . . . . . . . . . . . . . . . 26
Coroutines under the hood . . . . . . . . . . . . . . . . . . 38
Coroutines: built-in support vs library . . . . . . . . . . . 56

Part 2: Kotlin Coroutines library . . . . . . . . . . . . . . . . 58


Coroutine builders . . . . . . . . . . . . . . . . . . . . . . 59
Coroutine context . . . . . . . . . . . . . . . . . . . . . . 75
Jobs and awaiting children . . . . . . . . . . . . . . . . . . 87
Cancellation . . . . . . . . . . . . . . . . . . . . . . . . . 100
Exception handling . . . . . . . . . . . . . . . . . . . . . 115
Coroutine scope functions . . . . . . . . . . . . . . . . . . 125
Dispatchers . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Constructing a coroutine scope . . . . . . . . . . . . . . . 162
The problem with shared state . . . . . . . . . . . . . . . . 172
Testing Kotlin Coroutines . . . . . . . . . . . . . . . . . . 186

Part 3: Channel and Flow . . . . . . . . . . . . . . . . . . . . 219


Channel . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Actors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Hot and cold data sources . . . . . . . . . . . . . . . . . . 245
Flow introduction . . . . . . . . . . . . . . . . . . . . . . 253
Flow building . . . . . . . . . . . . . . . . . . . . . . . . . 264
Flow lifecycle functions . . . . . . . . . . . . . . . . . . . 276
Flow processing . . . . . . . . . . . . . . . . . . . . . . . 287
SharedFlow and StateFlow . . . . . . . . . . . . . . . . . . 310

Ending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
Introduction 1

Introduction

Why do you want to learn about Kotlin Coroutines? I like to ask my


workshop attendees this question. “Because they’re cool” and “Be-
cause everyone is talking about them” are common answers. Then I
dive deeper and I hear “because they are lighter threads”, “because
they are easier than RxJava”, or “because they allow concurrency
while allowing our code to have an imperative style”. However,
coroutines are much more than that. They are the holy grail of con-
currency. As a concept, they have been known in Computer Science
since the 1960s, but in mainstream programming they have only
been used in a very limited form (like async/await). This changed
with Golang, which introduced much more general-purpose corou-
tines. Kotlin built on that, creating what I believe is currently the
most powerful and practical implementation of this idea.
The importance of concurrency is growing, but the classic tech-
niques are not enough. Current trends suggest that coroutines are
the direction in which our industry is clearly heading, and Kotlin
Coroutines are a very solid step. Let me show them to you, with
examples of how well they help in common use cases. I hope you will
have a lot of fun reading this book.

Who is this book for?

As a developer experienced in both backend and Android, in this


book I try to mainly focus on these two perspectives. These are
currently the two major industry applications of Kotlin, and it can
be seen that coroutines were largely designed to suit these use cases
well¹. So, you might say that this book is primarily designed for
Android and backend developers, but it should be just as useful for
other developers using Kotlin.
This book assumes that readers know Kotlin well. If you do not, I
recommend starting with Kotlin in Action by Dmitry Jemerov and
Svetlana Isakova.

¹Google’s Android team cooperated in designing and creating


some features we will present in this book.
Introduction 2

The structure of this book

The book is divided into the following parts:

• Part 1: Understanding Kotlin Coroutines - dedicated to ex-


plaining what Kotlin Coroutines are and how they really work.
• Part 2: Kotlin Coroutines library - explaining the most impor-
tant concepts from the kotlinx.coroutines library and how to
use them well.
• Part 3: Channel and Flow - focused on Channel and Flow from
the kotlinx.coroutines library.

What will be covered?

This book is based on a workshop I conduct. During its iterations I


have been able to observe what interested attendees and what did not.
These are the elements that are most often mentioned by attendees:

• How do coroutines really work? (Part 1)


• How to use coroutines in practice? (Part 2 and 3)
• What are the best practices? (Part 2 and 3)
• Testing Kotlin coroutines (Testing Kotlin Coroutines in Part 2)
• What is Flow and how does it work? (Part 3)

Conventions

When I use a concrete element from code, I will use code-font. When
naming a concept, I will capitalize the word. To reference an arbi-
trary element of some type, I will use lowercase. For example:

• Flow is a type or an interface, it is printed with code-font (like


in “Function needs to return Flow”);
• Flow represents a concept, so it starts with an uppercase letter
(like in “This explains the essential difference between Chan-
nel and Flow”);
• a flow is an instance, like a list or a set, therefore it is in
lowercase (like in “Every flow consists of a few elements”).

Another example: List means an interface or a type (“The type of l is


List”); List represents a concept (a data structure), while a list is one
of many lists (“the list variable holds a list”).
I have used American English in the book, except for the spelling
of “cancellation/cancelled”, which I chose due to the spelling of the
“Cancelled” coroutine state.
Introduction 3

Code conventions

Most of the presented snippets are executable code with no import


statements. In the online version of this book on the Kt. Academy
website, most snippets can be executed, so readers can play with the
code.
Snippet results are presented using the println function. The result
will often be placed at the end of these snippets in comments. If there
is a delay between output lines, it will be shown in brackets. Here is
an example:

suspend fun main(): Unit = coroutineScope {


launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
// Hello,
// (1 sec)
// World!

Sometimes, some parts of code or a result are shortened with .... In


such cases, you can read it as “there should be more here, but it is not
relevant to the example”.

launch(CoroutineName("Name1")) { ... }
launch(CoroutineName("Name2") + Job()) { ... }

In some cases, I will show comments next to the line that prints them.
I do this when the order is clear:

suspend fun main(): Unit = coroutineScope {


println("Hello,") // Hello,
delay(1000L) // (1 sec)
println("World!") // World!
}

In a few snippets I have added a number after the line to more easily
explain the snippet’s behavior. This is what it might look like:
Introduction 4

suspend fun main(): Unit = coroutineScope {


println("Hello,") // 1
delay(1000L) // 2
println("World!") // 3
}

At 1 we print “Hello,”, then we wait for a second because line 2


contains delay, and we print “World!” at line 3.
Introduction 5

Acknowledgments

This book would not be so good without the reviewers’ great sugges-
tions and comments. I would like to thank all of them. Here is the
whole list of reviewers, starting from the most active ones.

Nicola Corti - a Google Developer Expert for


Kotlin. He has been working with the language
since before version 1.0, and he is the main-
tainer of several open-source libraries and
tools for mobile developers (Detekt, Chucker,
AppIntro). He’s currently working in the React
Native core team at Meta, building one of the
most popular cross-platform mobile frameworks. Furthermore, he
is an active member of the developer community. His involvement
goes from speaking at international conferences to being a member
of CFP committees and supporting developer communities across
Europe. In his free time, he also loves baking, podcasting, and run-
ning.

Garima Jain - a Google Developer Expert in


Android from India. She is also known around
the community as @ragdroid. Garima works
as a Principal Android Engineer at GoDaddy.
She is also an international speaker and an
active technical blogger. She enjoys interact-
ing with other people from the community
and sharing her thoughts with them. In her leisure time, she loves
watching television shows, playing TT, and basketball. Due to her
love for fiction and coding, she loves to mix technology with fiction
and then shares her ideas with others through talks and blog posts.

Ilmir Usmanov - a software developer at Jet-


Brains, working on coroutine support in the
Kotlin compiler since 2017. Was responsible
for stabilization and implementation of the
coroutines design. Since then, he has moved
to other features, namely inline classes. Cur-
rently, his work with coroutines is limited to
bug fixing and optimization, since coroutines as a language feature
is complete and stable and does not require much attention.

You might also like