14 Coroutines

 

This chapter covers

  • The concepts of concurrency and parallelism
  • Suspending functions as the basic building blocks for concurrent operations in Kotlin
  • Kotlin’s approach to concurrent programming with coroutines

Modern programs rarely only do one thing at a time; networked applications may need to make or serve multiple network requests but shouldn’t wait for each network request to finish before starting the next one. Mobile and desktop apps may need to do anything from querying on-device databases, to using sensors, to communicating with other devices—all while redrawing their user interface 60 times per second or more.

To handle this, modern applications need to do multiple things at the same time, asynchronously. That means developers need tools to allow different operations to execute independently without blocking each other as well as coordinate and synchronize between concurrent tasks.

In this chapter, we’ll take a look at Kotlin’s approach to doing these kinds of asynchronous computations using coroutines. Coroutines allow you to write code that can be both concurrent and parallel.

14.1 Concurrency vs. parallelism

Before we dive deeper into concurrent programming with Kotlin, let’s briefly define what we actually mean when we talk about concurrency—as well as its relationship to the concept of parallelism.

14.2 Concurrency the Kotlin way: Suspending functions and coroutines

14.3 Comparing threads and coroutines

14.4 Functions that can pause: Suspending functions

14.4.1 Code written with suspending functions looks sequential

14.5 Comparing coroutines to other approaches

14.5.1 Calling a suspending function

14.6 Entering the world of coroutines: Coroutine builders

14.6.1 From regular code into the realm of coroutines: The runBlocking function

14.6.2 Creating start-and-forget coroutines: The launch function

14.6.3 Awaitable computations: The async builder

14.7 Deciding where your code should run: Dispatchers