As i understand.
remember
just cache result of computation to keep result instance between compositions. Any object. And MutableState
instance. And this is why it is useful.
val text = remember{ "" }
just cache empty string.
val text = mutableStateOf("")
create MutableState
and compose
observe it value, but not cache MutableState
instance, so it will be re-created on next recomposition (of course if recomposition will happen in this place)
for example:
val state: MutableState<Int> = mutableStateOf(1)
println(state.toString())
Text(
modifier = Modifier.clickable { state.value += 1 },
text = "${state.value}",
)
the text will always be 1, because every recomposition re-creates state
and the output will be:
MutableState(value=1)@227069120
MutableState(value=1)@104526071
MutableState(value=1)@915621104
MutableState(value=1)@580489706
remember
caches MutableState
object and keep same instance on every recomposition
val state: MutableState<Int> = remember { mutableStateOf(1) }
println(state.toString())
Text(
modifier = Modifier.clickable { state.value += 1 },
text = "${state.value}",
)
work as expected.
MutableState(value=2)@1121832406
MutableState(value=3)@1121832406
MutableState(value=4)@1121832406
MutableState(value=5)@1121832406
remember(key)
val key = remember { 0 }
var state by remember(key) { mutableStateOf(1) }
println(state.toString())
Text(
modifier = Modifier.clickable { state += 1 },
text = "${state}",
)
Works like the example above, even though the key
doesn't change. It's because in case of a MutableState
, not the value is cached, but the instance of MutableState
itself with the value
field, which changes.
changing key
value will recreate MutableState
instance