StateFlow
A SharedFlow that represents a read-only state with a single updatable data value that emits updates to the value to its collectors. A state flow is a hot flow because its active instance exists independently of the presence of collectors. Its current value can be retrieved via the value property.
State flow never completes. A call to Flow.collect on a state flow never completes normally, and neither does a coroutine started by the Flow.launchIn function. An active collector of a state flow is called a subscriber.
A mutable state flow is created using MutableStateFlow(value) constructor function with the initial value. The value of mutable state flow can be updated by setting its value property. Updates to the value are always conflated. So a slow collector skips fast updates, but always collects the most recently emitted value.
StateFlow is useful as a data-model class to represent any kind of state. Derived values can be defined using various operators on the flows, with combine operator being especially useful to combine values from multiple state flows using arbitrary functions.
For example, the following class encapsulates an integer state and increments its value on each call to inc:
class CounterModel {
private val _counter = MutableStateFlow(0) // private mutable state flow
val counter = _counter.asStateFlow() // publicly exposed as read-only state flow
fun inc() {
_counter.update { count -> count + 1 } // atomic, safe for concurrent use
}
}Having two instances of the above CounterModel class one can define the sum of their counters like this:
val aModel = CounterModel()
val bModel = CounterModel()
val sumFlow: Flow<Int> = aModel.counter.combine(bModel.counter) { a, b -> a + b }As an alternative to the above usage with the MutableStateFlow(...) constructor function, any coldFlow can be converted to a state flow using the stateIn operator.
Strong equality-based conflation
Values in state flow are conflated using Any.equals comparison in a similar way to distinctUntilChanged operator. It is used to conflate incoming updates to value in MutableStateFlow and to suppress emission of the values to collectors when new value is equal to the previously emitted one. State flow behavior with classes that violate the contract for Any.equals is unspecified.
State flow is a shared flow
State flow is a special-purpose, high-performance, and efficient implementation of SharedFlow for the narrow, but widely used case of sharing a state. See the SharedFlow documentation for the basic rules, constraints, and operators that are applicable to all shared flows.
State flow always has an initial value, replays one most recent value to new subscribers, does not buffer any more values, but keeps the last emitted one, and does not support resetReplayCache. A state flow behaves identically to a shared flow when it is created with the following parameters and the distinctUntilChanged operator is applied to it:
// MutableStateFlow(initialValue) is a shared flow with the following parameters:
val shared = MutableSharedFlow(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
shared.tryEmit(initialValue) // emit the initial value
val state = shared.distinctUntilChanged() // get StateFlow-like behaviorUse SharedFlow when you need a StateFlow with tweaks in its behavior such as extra buffering, replaying more values, or omitting the initial value.
StateFlow vs ConflatedBroadcastChannel
Conceptually, state flow is similar to ConflatedBroadcastChannel and is designed to completely replace it. It has the following important differences:
StateFlowis simpler, because it does not have to implement all the Channel APIs, which allows for faster, garbage-free implementation, unlikeConflatedBroadcastChannelimplementation that allocates objects on each emitted value.StateFlowalways has a value which can be safely read at any time via value property. UnlikeConflatedBroadcastChannel, there is no way to create a state flow without a value.StateFlowhas a clear separation into a read-onlyStateFlowinterface and a MutableStateFlow.StateFlowconflation is based on equality like distinctUntilChanged operator, unlike conflation inConflatedBroadcastChannelthat is based on reference identity.StateFlowcannot be closed likeConflatedBroadcastChanneland can never represent a failure. All errors and completion signals should be explicitly materialized if needed.
StateFlow is designed to better cover typical use-cases of keeping track of state changes in time, taking more pragmatic design choices for the sake of convenience.
To migrate ConflatedBroadcastChannel usage to StateFlow, start by replacing usages of the ConflatedBroadcastChannel() constructor with MutableStateFlow(initialValue), using null as an initial value if you don't have one. Replace send and trySend calls with updates to the state flow's MutableStateFlow.value, and convert subscribers' code to flow operators. You can use the filterNotNull operator to mimic behavior of a ConflatedBroadcastChannel without initial value.
Concurrency
All methods of state flow are thread-safe and can be safely invoked from concurrent coroutines without external synchronization.
Operator fusion
Application of flowOn, conflate, buffer with CONFLATED or RENDEZVOUS capacity, distinctUntilChanged, or cancellable operators to a state flow has no effect.
Implementation notes
State flow implementation is optimized for memory consumption and allocation-freedom. It uses a lock to ensure thread-safety, but suspending collector coroutines are resumed outside of this lock to avoid dead-locks when using unconfined coroutines. Adding new subscribers has O(1) amortized cost, but updating a value has O(N) cost, where N is the number of active subscribers.
Not stable for inheritance
The StateFlow interface is not stable for inheritance in 3rd party libraries, as new methods might be added to this interface in the future, but is stable for use. Use the MutableStateFlow(value) constructor function to create an implementation.
Properties
Inheritors
Extensions
Returns a flow which checks cancellation status on each emission and throws the corresponding cancellation cause if flow collector was cancelled. Note that flow builder and all implementations of SharedFlow are cancellable by default.
Catches exceptions in the flow completion and calls a specified action with the caught exception. This operator is transparent to exceptions that occur in downstream flow and does not catch exceptions that are thrown to cancel the flow.
Terminal flow operator that collects the given flow with a provided action that takes the index of an element (zero-based) and the element. If any exception occurs during collect or in the provided flow, this exception is rethrown from this method.
Returns flow where all subsequent repetitions of the same value are filtered out.
Returns flow where all subsequent repetitions of the same value are filtered out, when compared with each other via the provided areEquivalent function.
Returns flow where all subsequent repetitions of the same key are filtered out, where key is extracted with keySelector function.
The terminal operator that returns the first element emitted by the flow and then cancels flow's collection. Throws NoSuchElementException if the flow was empty.
The terminal operator that returns the first element emitted by the flow matching the given predicate and then cancels flow's collection. Throws NoSuchElementException if the flow has not contained elements matching the predicate.
The terminal operator that returns the first element emitted by the flow and then cancels flow's collection. Returns null if the flow was empty.
Returns a flow that switches to a new flow produced by transform function every time the original flow emits a value. When the original flow emits a new value, the previous flow produced by transform block is cancelled.
Flattens the given flow of flows into a single flow in a sequential manner, without interleaving nested flows.
Flattens the given flow of flows into a single flow with a concurrency limit on the number of concurrently collected flows.
The terminal operator that returns the last element emitted by the flow or null if the flow was empty.
Terminal flow operator that launches the collection of the given flow in the scope. It is a shorthand for scope.launch { flow.collect() }.
Returns a flow that invokes the given actionafter this shared flow starts to be collected (after the subscription is registered).
Creates a produce coroutine that collects the given flow.
Retries collection of the given flow when an exception occurs in the upstream flow and the predicate returns true. The predicate also receives an attempt number as parameter, starting from zero on the initial call. This operator is transparent to exceptions that occur in downstream flow and does not retry on exceptions that are thrown to cancel the flow.
Converts a coldFlow into a hotSharedFlow that is started in the given coroutine scope, sharing emissions from a single running instance of the upstream flow with multiple downstream subscribers, and replaying a specified number of replay values to new subscribers. See the SharedFlow documentation for the general concepts of shared flows.
The terminal operator that awaits for one and only one value to be emitted. Throws NoSuchElementException for empty flow and IllegalStateException for flow that contains more than one element.
The terminal operator that awaits for one and only one value to be emitted. Returns the single value or null, if the flow was empty or emitted more than one value.
Converts a coldFlow into a hotStateFlow that is started in the given coroutine scope, sharing the most recently emitted value from a single running instance of the upstream flow with multiple downstream subscribers. See the StateFlow documentation for the general concepts of state flows.
Starts the upstream flow in a given scope, suspends until the first value is emitted, and returns a hotStateFlow of future emissions, sharing the most recently emitted value from this running instance of the upstream flow with multiple downstream subscribers. See the StateFlow documentation for the general concepts of state flows.
Collects given flow into a destination
Collects given flow into a destination
Collects given flow into a destination
Returns a flow that produces element by transform function every time the original flow emits a value. When the original flow emits a new value, the previous transform block is cancelled, thus the name transformLatest.
Returns a flow that wraps each element into IndexedValue, containing value and its index (starting from zero).