chapter seventeen

17 Flow operators

 

This chapter covers

  • Operators used to transform and work with flows
  • Intermediate and terminal operators
  • Building custom flow operators

17.1 Manipulating flows with flow operators

In the previous chapter, you have gotten to know flows as the higher-level abstraction that allows you to work with multiple, sequential values over time while leveraging Kotlin’s concurrency machinery. In this chapter, we’ll discuss how to manipulate and transform them. You’ve already seen that Kotlin provides a vast selection of operators that you can use to manipulate collections (as we’ve discussed in Chapter 5 and Chapter 6). Likewise, you can use operators to transform flows.

Just like with sequences, you distinguish between the intermediate flow operators and terminal flow operators, analogous to our discussion in Section 6.2.1: Intermediate operators return another, modified flow, without actually running any of the code yet. Terminal operators return a result – like a collection, an individual element from the flow, a computed value, or no value at all – collecting the flow and executing the actual code.

Figure 17.1 You distinguish between intermediate and terminal flow operators. Where intermediate operators return a modified flow, terminal operators return an actual result. They do so by executing the code in the flow.
CH17 F01 Isakova

17.2 Intermediate operators are applied to an upstream flow and return a downstream flow

17.2.1 Emitting arbitrary values for each upstream element: transform

17.2.2 The take operator family can cancel a flow

17.2.3 Hooking into flow phases with onStart, onEach, onCompletion, and onEmpty

17.2.4 Buffering elements for downstream operators and collectors: buffer

17.2.5 Throwing away intermediate values: conflate

17.2.6 Filtering out values on a timeout: debounce

17.2.7 Switching the coroutine context on which a flow is executed: flowOn

17.3 Creating custom intermediate operators

17.4 Terminal operators execute the upstream flow and may compute a value

17.4.1 Frameworks provide custom operators

17.5 Summary