```data class Car(val name: String) @Composable p...
# compose
t
Copy code
data class Car(val name: String)

@Composable
private fun Test() {
    var car by remember { mutableStateOf(Car("Audi")) }
    var remCar = remember { car }
    LaunchedEffect(car) {
        remCar = car
    }
    println("remCar is `${remCar.name}`")
    Button(
        onClick = {
            car = Car("BMW - ${System.currentTimeMillis()}")
        }
    ) {
        Text("CHANGE CAR")
    }
}
Pressing
CHANGE CAR
button always prints
remCar is Audi
Why it’s not printing
BMW
? 🤔
1
j
Because you remember a value that is captured once
You need to use derivedStateOf
or add
car
as a key to the second
remember
oh i missed the
LaunchedEffect
, but it's not a
State
so writes to it presumably won't trigger recomposition
t
Yeah, but it should print
BMW
for the next recomposition, right?
j
It will not because when the function re-runs the
remember
will re-read the original
car
value from the slot table and it will always reset to the Audi
t
Ooo 😮 So basically, we can’t change a
remember
-ed value like this
j
That's right. Because it's basically a positional marker into a separate storage mechanism. All you do when you overwrite the local is overwrite the value that was read. You do not overwrite the backing storage location.
k
It won't work because changing the value of
remCar
is not actually changing the value of the
mutableStateOf
, that's a misconception because the setter of
car
is not actually just setting a variable but updating the state, also you don't need to remember
car
, it's been already remembered.
j
When you remember a
State
the backing storage contains a reference to the
State
instance rather than a raw value. This is why changes to the
State
are reflected on future recompositions. The
remember
reads out the same
State
instance each time but the value held by that
State
is what changes.
t
Ohhkay.. Understood. Thank for the explanation guys 🙌