Day161 — mutableStateOf() in android compose
--
Here records the note I took when reading this article.
val stringState = remember { mutableStateOf("") }
It “remember” the value so it won’t be lost after recomposition.
Composable functions can use the
remember
API to store an object in memory. A value computed byremember
is stored in the Composition during initial composition, and the stored value is returned during recomposition.
similar to "lazy"
lazy
is bound to a class scope, remember
is bound to a composable function.
The first call to
get()
executes the lambda passed tolazy()
and remembers the result. Subsequent calls toget()
simply return the remembered result.
not always recompose
If the value
is the same, nothing happens.
If the value
isn’t read by anyone, nothing happens.
If the value
changes, all composables that read this value
will be recomposed.
derivedStateOf
derivedStateOf {}
should be used when your state or key is changing more than you want to update your UI.
before:
@Composable
private fun Counter() {
val counterState = remember { mutableStateOf(0) }
Button(
onClick = { counterState.value = counterState.value + 1 }
) {
Text(counterState.value.toString())
}
if (counterState.value >= 10) Text("Hurray!")
}
after:
@Composable
private fun CounterWithDerivedState() {
val counterState = remember { mutableStateOf(0) }
val showHurrayState = remember {
derivedStateOf { counterState.value > 10 }
}
Button(
onClick = { counterState.value = counterState.value + 1 }
) {
Text(counterState.value.toString())
}
if (showHurrayState.value) Text("Hurray!")
}
without derivedStateOf
Introducing another MutableState
also works, but it is not recommended.
@Composable
private fun CounterWithSecondMutableState() {
val counterState = remember { mutableStateOf(0) }
val showHurrayState = remember { mutableStateOf(false) }
Button(
onClick = {
counterState.value = counterState.value + 1
showHurrayState.value = counterState.value >= 10
}
) {
Text(counterState.value.toString())
}
if (showHurrayState.value) Text("Hurray!")
}
rememberSaveable
similar to SavedInstanceState
.
rememberSaveable
saves the calculatedvalue
into aBundle
(if it’s possible) on configuration change and can therefore restore it when theActivity
orFragment
got recreated. For example on orientation change, split screen, or process death.