Flow Operators
KOTLIN › Flow
Shaping a stream: transform, the Latest family, combine and zip, timing operators, and the ends of a flow.
Flow operators are examined by problem rather than by name: an interviewer describes a search box, or two inputs that must be recombined, and expects the right operator back. Expect to distinguish the pairs candidates swap, combine against zip and debounce against sample, and to know that transform is the general case map and filter are built from. Strong answers also know that take cancels the upstream, that the Latest family only helps when the work it interrupts actually suspends, and that onCompletion observes while catch handles.
What this covers
- Cold vs hot flows: each collector re-runs a cold flow's producer block independently
- Intermediate operators return a Flow lazily; terminal operators trigger collection
- transform is the general case: it may emit any number of values per input, which map and filter specialise
- onEach runs a side effect and passes the value through; mapNotNull is map plus filter in one step
- debounce waits for silence and emits nothing on a continuous feed; sample emits on a timer
- The Latest family (mapLatest, transformLatest, flatMapLatest, collectLatest) cancels in-progress work per new value
- Cancellation is cooperative, so the Latest family does nothing for a transform with no suspension points
- take cancels the upstream once it has its quota, which is how an infinite flow can terminate
- onStart can emit before the first value, onEmpty fires when nothing arrived, onCompletion runs on every ending
- onCompletion observes the failure but does not handle it: only catch can recover
- combine fires when either side emits; zip waits for a value from each and ends with the shorter flow
- launchIn is exactly scope.launch { collect() }, which is why the work moves into onEach
Study this topic
- Flow Operators explained: the guided lesson
- 18 practice quiz questions
- Flow Operators interview questions and answers