derivedStateOf
@StateFactoryMarker
public fun <T> derivedStateOf(calculation: () -> T): State<T>
Creates a State object whose State.value is the result of calculation. The result of
calculation will be cached in such a way that calling State.value repeatedly will not cause
calculation to be executed multiple times, but reading State.value will cause all State
objects that got read during the calculation to be read in the current Snapshot, meaning that
this will correctly subscribe to the derived state objects if the value is being read in an
observed context such as a Composable function. Derived states without mutation policy trigger
updates on each dependency change. To avoid invalidation on update, provide suitable
SnapshotMutationPolicy through derivedStateOf overload.
Parameters
| calculation | the calculation to create the value this state object represents. |
@StateFactoryMarker
public fun <T> derivedStateOf(policy: SnapshotMutationPolicy<T>, calculation: () -> T): State<T>
Creates a State object whose State.value is the result of calculation. The result of
calculation will be cached in such a way that calling State.value repeatedly will not cause
calculation to be executed multiple times, but reading State.value will cause all State
objects that got read during the calculation to be read in the current Snapshot, meaning that
this will correctly subscribe to the derived state objects if the value is being read in an
observed context such as a Composable function.
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. |
Code Examples
DerivedStateSample
@Suppress("CanBeVal", "unused")
@Composable
fun DerivedStateSample() {
@Composable
fun CountDisplay(count: State<Int>) {
Text("Count: ${count.value}")
}
@Composable
fun Example() {
var a by remember { mutableStateOf(0) }
var b by remember { mutableStateOf(0) }
val sum = remember { derivedStateOf { a + b } }
// Changing either a or b will cause CountDisplay to recompose but not trigger Example
// to recompose.
CountDisplay(sum)
}
}
