How am I supposed to use `mutableStateListOf`? I h...
# compose
m
How am I supposed to use
mutableStateListOf
? I have a
DisposableEffect(someStateList)
but it doesn't get re-triggered when I add to/remove from the list. What's the intended use-case?
s
It's likely that the surrounding composable is recomposing, but the list value is the same as before (because you are using the same state list as key). I think you want
someStateList.toList
here
z
If you’re doing something with the list in the effect, you can avoid recomposing by reading your list in something like snapshotFlow. If you really want to recompose though, and have to call
toList
, then why not just store an immutable list in a
mutableStateOf
?
m
I see, I was hoping mutableStateListOf was a way to handle mutations to a MutableList in Compose, but I guess swapping out lists is an okay alternative.
z
I was hoping mutableStateListOf was a way to handle mutations to a MutableList in Compose
It is.
If you're doing something like this:
Copy code
DisposableEffect(someStateList) { <-- This doesn't read the list and the instance is always the same, so the effect will never restart.
  someStateList.forEach { … } <-- This will read the current value of the list, but not restart.
}
Then you have 2 options. First, what Andrei suggested:
Copy code
DisposableEffect(someStateList.toList()) { <-- This is now a state read and will return a different instance when it changes.
  someStateList.forEach { … }
}
And if you want to avoid recomposing entirely:
Copy code
LaunchedEffect(someStateList) {
  snapshotFlow { <-- This lambda will restart whenever the list changes.
    someStateList.forEach { … }
  }.collect()
}
1