Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 134 ยท Coroutines

StateFlow and SharedFlow

Learn Kotlin StateFlow and SharedFlow - hot flows, MutableStateFlow as observable state, replay and buffers, tryEmit, stateIn, shareIn and SharingStarted, with runnable examples and common pitfalls.

A cold flow starts from scratch for every collector. That is perfect for "load this list", but wrong for things that exist independently of who is watching: the current user, the score of a game, a stream of button clicks. For those you want a hot flow: one source of truth that is already running, and any number of collectors that join and leave.

Kotlin gives you two hot flows. StateFlow holds one value that changes over time ("state"). SharedFlow broadcasts events to everyone who is currently listening ("events"). They are the usual way to expose observable data from a class, in Android view models, in servers and in plain Kotlin programs. This lesson follows flows and is followed by shared mutable state.

StateFlow: observable state

A MutableStateFlow always has a current value. Writers set value, readers either read value once or collect to be told about every change.

Kotlin MutableStateFlow basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A new collector receives the current value immediately (observed 0), and then each new value. A StateFlow never completes: collect on it waits forever, so you cancel the coroutine that collects (here watcher.cancel()), or the scope it lives in.

start = CoroutineStart.UNDISPATCHED runs the collector until its first suspension immediately, so it has certainly subscribed before we change the value. In normal code you do not need this; we use it to make the output deterministic.

Conflation and equality

StateFlow is a flow with two special rules:

  1. It is conflated: a slow collector sees only the latest value, never a backlog. States that changed twice between two collector runs are seen once.
  2. It ignores equal values. Setting a value equal (==) to the current one does not notify anybody.
Kotlin StateFlow skips repeats and intermediate values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

loading is never observed: the collector had no chance to run between the two assignments, so it saw only the latest state. That is the right behavior for state (the old one is already stale), and the wrong one for events, where each occurrence counts. For events, use SharedFlow.

Because of equality, a StateFlow<List<Int>> does not notice if you mutate the same list instance and assign it again. Keep state immutable and assign a new object (state.value = list + item).

update: safe read-modify-write

state.value = state.value + 1 is not atomic: two coroutines may read the same old value. Use update { }, which retries until the swap succeeds, or getAndUpdate, updateAndGet:

Kotlin update is atomic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

With 100 coroutines each adding 1000 times the result is exactly 100000. Replace update with counter.value++ and the total would be unpredictable (see shared mutable state).

The read-only pattern

A class should hold the mutable flow privately and expose a read-only StateFlow, so outsiders can observe state but only the class can change it. asStateFlow() creates the read-only view:

Kotlin Encapsulated state in a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The collector sees the whole story: empty cart, one item, two items, empty again. The underscore-prefixed backing property (_state) is a standard Kotlin convention for this.

SharedFlow: broadcasting events

A MutableSharedFlow has no current value. It sends every emit to all collectors that are subscribed at that moment. Without subscribers an emitted value is simply lost, unless you configure a replay.

Kotlin MutableSharedFlow: everyone gets every event

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Unlike a channel, where each value goes to one consumer, here both collectors receive both events. Also unlike StateFlow, emit does not drop equal values.

Late subscribers and replay

By default a collector that joins late misses what was sent before. replay = n keeps the last n values and hands them to every new subscriber.

Kotlin replay for late subscribers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The late collector of replay2 immediately received 3 and 4, the two most recent values. The one without replay received nothing. A StateFlow behaves like a shared flow with replay = 1, conflation and equality checking built in.

Buffers and what happens when a collector is slow

emit is a suspending function. By default (extraBufferCapacity = 0, onBufferOverflow = SUSPEND) it waits until every subscriber has taken the value, so one slow collector slows the producer down. You can configure the opposite:

  • extraBufferCapacity = n: allow n undelivered values per slow subscriber before emit suspends.
  • onBufferOverflow = DROP_OLDEST or DROP_LATEST: never suspend; sacrifice values for the slow collector.

For events that come from non-suspending code (a button callback), use tryEmit. It returns false instead of suspending when it cannot deliver. With the default settings and a subscriber waiting, tryEmit fails, so such flows need a buffer:

Kotlin tryEmit needs a buffer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both flows had one subscriber, not yet at the point of receiving anything, because the collectors had not run since the emits. The strict flow rejected all three values (false): without a buffer, tryEmit cannot hand over a value to a subscriber that is not ready. The flow with extraBufferCapacity = 8 accepted all three (true).

Turning cold flows hot: stateIn and shareIn

You often start from a cold flow (a database query, a sensor) and want to share one upstream run among many collectors. stateIn and shareIn convert a cold flow into a hot one inside a scope you give them.

Kotlin One upstream, two collectors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The cold flow ran twice, the shared one only once, however many collectors there are. stateIn(scope, started, initialValue) needs an initial value because a StateFlow always has one; shareIn(scope, started, replay) does not.

SharingStarted: when does the upstream run?

The started parameter decides when the upstream is active:

Policy Upstream is running
SharingStarted.Eagerly immediately, until the scope is cancelled
SharingStarted.Lazily after the first subscriber, forever
SharingStarted.WhileSubscribed(stopTimeoutMillis, replayExpirationMillis) only while there is at least one subscriber, plus an optional grace period

WhileSubscribed saves resources when nobody is looking. On Android, WhileSubscribed(5000) is the common choice: a 5-second grace period survives a screen rotation without restarting the upstream. In a server the grace period is chosen according to how expensive a restart is.

Kotlin WhileSubscribed stops idle upstreams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The upstream did not start until the first subscriber arrived, and stopped when the last one left. Starting it was exactly the cost of having a listener.

StateFlow or SharedFlow?

StateFlow SharedFlow
Models state: "what is the value now" events: "something happened"
Initial value required none
Replay the latest value, always configurable (default 0)
Equal values ignored delivered
Slow collector sees only the latest configurable buffer and policy
Completes never never

If a missed value is a bug (a payment confirmation, "navigate to screen X"), a StateFlow is the wrong tool, since the value can be conflated or consumed twice on re-subscription. Use a Channel (one consumer) or a SharedFlow with a buffer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A new collector subscribes to a StateFlow whose value is 5. What does it receive first?

    A StateFlow always has a current value and delivers it to every new collector right away.
  2. 2. You set state.value = "a" when the value is already "a". What happens?

    StateFlow compares new values with ==, and does not emit equal ones.
  3. 3. Which call is the correct, thread-safe way to increment a MutableStateFlow<Int>?

    update performs a compare-and-set loop, so concurrent updates are not lost.
  4. 4. Two collectors listen to the same MutableSharedFlow. You call emit("x"). How many collectors receive it?

    A SharedFlow broadcasts to all current subscribers, unlike a channel, which delivers to a single receiver.
  5. 5. What is the purpose of SharingStarted.WhileSubscribed(5000)?

    The upstream is active while there are subscribers; the timeout is a grace period that avoids restarting it for short gaps such as a configuration change.

Summary

  • Hot flows exist independently of collectors. StateFlow models state; SharedFlow models events.
  • MutableStateFlow(initial) has value, replays the latest value, conflates and ignores equal values; use update { } for safe changes and expose it with asStateFlow().
  • MutableSharedFlow(replay, extraBufferCapacity, onBufferOverflow) broadcasts to all subscribers; late subscribers get only the replay cache.
  • tryEmit is for non-suspending code and needs a buffer to succeed.
  • stateIn and shareIn turn a cold flow into a hot one that runs once for many collectors; WhileSubscribed stops the upstream when nobody listens.
  • Hot flows never complete: cancel the collecting coroutine.

Next: Shared Mutable State