Stream UI state with Kotlin Flow

8 steps · about 2 h · Intermediate

  1. Produce, transform and collect a flow (article, Android Developers, 25 min)

    Shows the producer, intermediary and consumer roles with a realistic repository example.

  2. Choose StateFlow or SharedFlow (article, Android Developers, 20 min)

    Explains hot flows, replay and when to convert a cold flow with stateIn or shareIn.

  3. Read the Flow contract (reference, kotlinx.coroutines API, 15 min)

    States context preservation and exception transparency, the two rules custom operators must keep.

  4. Understand StateFlow conflation (reference, kotlinx.coroutines API, 10 min)

    Explains why StateFlow drops intermediate values and compares equal values before emitting.

  5. Move upstream work off the main thread (reference, kotlinx.coroutines API, 10 min)

    flowOn changes the upstream dispatcher without breaking context preservation.

  6. Handle upstream errors with catch (reference, kotlinx.coroutines API, 10 min)

    Shows how catch sees only upstream failures and can emit a fallback value.

  7. Test flows with fakes and test dispatchers (article, Android Developers, 20 min)

    Covers collecting in tests, backgroundScope and testing StateFlow without timing flakiness.

  8. Assert flow emissions with Turbine (repo, GitHub, 10 min)

    A small library that turns a flow into awaitItem/awaitComplete assertions.