https://kotlinlang.org logo
#compose
Title
# compose
l

Lance Gao

02/18/2022, 6:27 AM
Hi, how to update composable when a list changes by
rember { mutableStateOf(mutableListOf<Int>())}
?
It does not work when I change the list.
m

mattinger

02/18/2022, 6:43 AM
are you mutating the actual list? state does not update unless you re-assign the state itself. ie, this will work:
Copy code
val state = remember { mutableStateOf(listOf<Int>()) }
state.value = state.value + 1
This creates a new list with the additional element appended to the end of it and reassigns the value in the state. This allows the observers (ie, the recomposer) to know that the value changed and things need recomposing. However, if you do this:
Copy code
state.value.add(1)
You are simply changing the data inside the list, which no one is observing. There's no way for the recomposer to know that anything changed.
I think a good rule of thumb is keep immutable objects inside of a MutableState. So in your case, you want the type to be:
MutableState<List<Int>>
and not
MutableState<MutableList<Int>>
l

Lance Gao

02/18/2022, 6:48 AM
Thanks for your reply! So I must assign
state
a new list to notify the recomposer right?
m

mattinger

02/18/2022, 6:48 AM
correct
l

Lance Gao

02/18/2022, 6:48 AM
Okay thanks a lot
m

mattinger

02/18/2022, 7:13 AM
mutableStateList is a special type of object that implements the StateObject interface. That interface is a hook into having mutable objects like this be able to inform observers of their changes. I still personally perfer to use a raw, immutable list than to use this special implementation
l

Lance Gao

02/18/2022, 7:41 AM
Ok thanks for your suggestion
c

Colton Idle

02/18/2022, 8:43 AM
This is also good if you haven't read it https://dev.to/zachklipp/two-mutables-dont-make-a-right-2kgp
☝️ 1
19 Views