map State
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 // 7Content copied to clipboard
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
valueand 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.