StateHolder

Holds a piece of UI/domain state and exposes it read-only, implementing the FLOW_010 backing property pattern: the MutableStateFlow is private, so external code can only change state through set and update.

Example:

class CounterViewModel {
private val holder = StateHolder(0)
val count: StateFlow<Int> = holder.state

fun increment() = holder.update { it + 1 }
}

It is a final class (not open): extending it could not add safety, and a final type keeps the guarantee that the mutable flow is never exposed by a subclass.

Rules: FLOW_010 (never expose MutableStateFlow/MutableSharedFlow publicly). See docs/BEST_PRACTICES_COROUTINES.md section 9.5.

Thread-safe: reads, set and update may be used from any thread.

Requires opting in to ExperimentalStructuredCoroutines.

Parameters

initial

the initial state.

Type Parameters

T

the state type.

See also

Constructors

Link copied to clipboard
constructor(initial: T)

Properties

Link copied to clipboard

Read-only view of the state. It is not a MutableStateFlow and cannot be cast back to one.

Link copied to clipboard
val value: T

Current value; same as state.value.

Functions

Link copied to clipboard
fun set(value: T)

Replaces the value. Prefer update when the new value depends on the current one. Like MutableStateFlow, equal values are conflated and not re-emitted.

Link copied to clipboard
fun update(transform: (T) -> T)

Atomically replaces the value with transform(current). transform may be re-invoked if another thread updates concurrently, so it must be side-effect free.