mapState

fun <T, R> StateFlow<T>.mapState(transform: (value: T) -> R): StateFlow<R>(source)

Returns a read-only StateFlow derived from this state flow using transform.

Every access to StateFlow.value reads the current source value once and invokes transform once. The transformed result is not cached between property reads. Every access to StateFlow.replayCache performs the same fresh computation and returns the result as a singleton list. Updating the source does not invoke transform unless the returned state flow is being collected or one of these properties is accessed.

Each collector independently invokes transform for source values observed by that collector. Collection follows StateFlow's strong equality-based conflation: a slow collector can skip intermediate transformed values, and a transformed value that is equal to the last emitted value is not emitted again. Property reads and collectors do not share transformed results.

transform can be invoked repeatedly and concurrently. To preserve StateFlow semantics, it must be deterministic, side-effect-free, safe for concurrent invocation, and must not throw. An exception from transform escapes the property access or fails the affected collection; it is not represented as a state value.

This operator is useful when a StateFlow result is required instead of the Flow returned by map.

See also