Tgo1014
05/18/2023, 1:08 PMremember
just to keep the value across recompositions? mutableStateOf
is not enough to trigger recompositions?
@Composable
@Preview
fun Test() {
var a by remember { mutableStateOf(false) }
var b by mutableStateOf(false)
val c by derivedStateOf { a && b }
Column {
Text(text = "A $a")
Text(text = "B $b")
Text(text = "C $c")
Button(onClick = { a = !a }) {
Text("A")
}
Button(onClick = { b = !b }) {
Text("B")
}
}
}
mikehearn
05/18/2023, 1:10 PMb
will be recreated from scratchremember{}
to stop that happening and ensure the object persists even across re-executions of the function. Yeah it's a bit weird. Think of the function as if it's a class and remember{}
as if it's a property, if that helps. Then you can see that b
will be just a normal local variable.Tgo1014
05/18/2023, 1:11 PMb
is a object that keep the value, no? So if I do b = !b
why it goes back to false? I don't think the entire screen is being recreated, no?krzysztof
05/18/2023, 1:20 PMb = !b
, will recompose Test()
again. This is because the Column
is inlined, so that the recomposition scope goes up to Test
itself. And calling Test
itself will create a new member variable b
with false
valuemikehearn
05/18/2023, 1:29 PMapplication{}
or setContent{}
on down is re-executed fresh. The only way to preserve data is either use global variables or use remember
.b
is not an object that keeps its value. A MutableState
is just an observable variable with fancy extras. It can trigger event handlers when it changes, but it has nothing to say about how long it lasts in the heap. It's no different to allocating any other object as a local variable.Tgo1014
05/18/2023, 1:33 PMb
it would just recompose what's using the value of b
🤔krzysztof
05/18/2023, 1:34 PMthe entire code fromis wrong statement in that regards and would be super duper inefficient to have in any ui frameworkorapplication{}
on down is re-executed fresh.setContent{}
Tgo1014
05/18/2023, 1:35 PMTest()
is not recomposed, so why would the value be lost? That's the bit I'm missingkrzysztof
05/18/2023, 1:36 PMb
value is read in a scope of itColumn {
Text(text = "A $a")
// Text(text = "B $b")
Text(text = "C $c")
Button(onClick = { a = !a }) {
Text("A")
}
Button(onClick = { b = !b }) {
Text("B ${b}") // note here
}
}
Then your b
will keep the value, until a
is changed.b
is no longer read within Test
scope, but rather in Button’s content
scope. a
is still read within Test
scope, so if that changes, compose calls Test
function againTgo1014
05/18/2023, 1:41 PMState
changes, Compose will retrigger everything from the earliest access point of the State
?krzysztof
05/18/2023, 1:42 PMmutableStateOf
) is read within that scope, compose will re-run that composable if that value changesTgo1014
05/18/2023, 1:44 PMkrzysztof
05/18/2023, 1:45 PMmikehearn
05/18/2023, 1:53 PM