16 Flows

 

This chapter covers

  • Working with flows as a model for sequential streams of values
  • Use cases for and differences between cold flows and hot flows

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.

16.1 Flows model sequential streams of values

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.

16.1.1 Flows allow you to work with elements as they are emitted

16.1.2 Different types of flows in Kotlin

16.2 Cold flows

16.2.1 Creating a cold flow with the flow builder function

16.2.2 Cold flows don’t do any work until collected

16.2.3 Cancelling the collection of a flow

16.2.4 Cold flows under the hood

16.2.5 Concurrent flows with channel flows

16.3 Hot flows

16.3.1 Shared flows broadcast values to subscribers

16.3.2 Keeping track of state in your system: State flow

16.3.3 Comparing state flows and shared flows

16.3.4 Hot, cold, shared, state: When to use which flow

Summary