Stream UI state with Kotlin Flow
8 steps · about 2 h · Intermediate
- Produce, transform and collect a flow (article, Android Developers, 25 min)
Shows the producer, intermediary and consumer roles with a realistic repository example.
- Choose StateFlow or SharedFlow (article, Android Developers, 20 min)
Explains hot flows, replay and when to convert a cold flow with stateIn or shareIn.
- Read the Flow contract (reference, kotlinx.coroutines API, 15 min)
States context preservation and exception transparency, the two rules custom operators must keep.
- Understand StateFlow conflation (reference, kotlinx.coroutines API, 10 min)
Explains why StateFlow drops intermediate values and compares equal values before emitting.
- Move upstream work off the main thread (reference, kotlinx.coroutines API, 10 min)
flowOn changes the upstream dispatcher without breaking context preservation.
- Handle upstream errors with catch (reference, kotlinx.coroutines API, 10 min)
Shows how catch sees only upstream failures and can emit a fallback value.
- Test flows with fakes and test dispatchers (article, Android Developers, 20 min)
Covers collecting in tests, backgroundScope and testing StateFlow without timing flakiness.
- Assert flow emissions with Turbine (repo, GitHub, 10 min)
A small library that turns a flow into awaitItem/awaitComplete assertions.