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 the same 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/or parallel.
14.1 Concurrency means doing multiple things simultaneously, parallelism means physically executing them at the same time
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.