mapState

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

Like map for a StateFlow, but the result is still a StateFlow, and no CoroutineScope is needed.

Example

val items = MutableStateFlow(listOf(Item(price = 3), Item(price = 4)))
val total: StateFlow<Int> = items.mapState { it.sumOf { item -> item.price } }
total.value // 7

Compared with map and stateIn

map returns a plain Flow, which has no value. map(...).stateIn(scope, ...) needs a scope and starts a coroutine. mapState computes the value when you read it, so it needs neither and is never out of date.

Watch out

  • transform runs on every read of value and on every new source value. Keep it fast, and free of side effects.

  • Collectors get a new value only when the result changes by equals.

See also