Flow: the Basics Flashcards
KOTLIN › Concurrency
- What is a Kotlin Flow?
- An asynchronous stream that produces zero, one, or many values over time, think of it as a List you receive one item at a time, or a Sequence that can suspend between items. Contrast with a suspend fun, which returns a single value once.
- What are the two halves of a Flow?
- The **producer** (the flow { } block, which calls emit(value) to hand out values one at a time) and the **collector** (whoever calls collect { }, whose lambda runs once per emitted value).
- What does emit() do?
- Inside a flow { } builder, emit(value) sends one value from the producer to the collector, then suspends until the collector's block finishes with that value before moving on.
- Does creating a Flow run any code?
- No. A Flow is cold and lazy, val f = flow { ... } only describes the stream. The producer block runs only when a terminal operator (collect, toList, first) starts it.
- Why must collect run inside a coroutine?
- collect is a suspend function, so it can only be called from a coroutine (e.g. viewModelScope.launch { ... }) or another suspend function.
- Can you call suspend functions inside flow { }?
- Yes, the builder is a suspending context, so you can call delay, network or database calls, etc. right before emit. That straight-line, no-callbacks style is Flow's main advantage over listeners.
- What does it mean that a Flow is *cold*?
- It runs on demand when collected, and re-runs its producer independently for every collector, nothing is shared by default. The opposite is a *hot* flow (always-on, shared), made with shareIn/stateIn.
- Flow vs a callback/listener API, what's the win?
- Straight-line suspending code instead of nested callbacks, built-in cancellation (collection stops when the coroutine is cancelled), and a rich operator set (map, filter, combine, …) for transforming the stream.