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 got 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 you can use to manipulate collections (as discussed in chapters 5 and 6). Likewise, you can use operators to transform flows.

Just like with sequences, you distinguish between the intermediate flow operators and terminal flow operators analogously to our discussion in chapter 6: 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 (visualized in figure 17.1).

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: The transform function

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: The buffer operator

17.2.5 Throwing away intermediate values: The conflate operator

17.2.6 Filtering out values on a timeout: The debounce operator

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

17.3 Creating custom intermediate operators

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