In the previous chapter, you have gotten to know coroutines and suspending functions as the basic abstraction used for concurrent programming in Kotlin. In this chapter, we will change our focus to a higher-level abstraction built on top of coroutines: flows, which allow you to work with multiple, sequential values over time while leveraging Kotlin’s concurrency machinery. In this chapter, we’ll discuss the ins and outs of flows. We’ll discuss the different types of flows and how to create, transform, and consume them.
As discussed in chapter 14, a suspending function can pause its execution, be it once or multiple times. However, it can only return a single value, for example, a primitive, an object, or a collection of objects. Listing 16.1 illustrates this: your suspending function createValues creates a list of three values. By introducing a delay of 1 second per element, you can simulate a longer-running computation. Running this code, you will notice that the function only returns once all values have been computed: after 3 seconds, you see all three values printed.