Function

computedStateOf

Creates a State object whose State.value is the result of calculation.

computedStateOf

Source set: Common
public fun <T> computedStateOf(
    policy: SnapshotMutationPolicy<T> = structuralEqualityPolicy(),
    calculation: () -> T,
): State<T>

Creates a State object whose State.value is the result of calculation. The calculation is executed each time the value is read and is not cached when re-reading the value. Reading the value of the state multiple times in the same snapshot will execute calculation each time, and the current snapshot will subscribe to the state objects referenced in the calculation.

Note that the calculation lambda may be called more times than State.value is read as part of managing the state and checking its validity.

If any of the referenced states are modified, reads of the state are only considered to be invalid if the calculation lambda returns a value that is not equal to the last value read by the observer, with equality being defined by the given policy. In composition, this notably means that invalidations triggered by reads in a computedStateOf will conditionally invalidate the body of the composable based on whether the new result of calculation is different from the last value read at that point. It's considered an error to use neverEqualPolicy with computedStateOf, as this defeats all skipping behavior provided by using a ComputedState.

A ComputedState should be preferred over a DerivedState when you don't need the caching behavior that DerivedState provides.

Parameters

policy mutation policy to control when changes to the calculation result trigger update.
calculation the calculation to create the value this state object represents.

Content updated: