Reputation: 14837
For a mutable state containing integer like this,
var data by rememberSaveable {
mutableStateOf(-1)
}
We can update data using
data = 5
And it would update the data and trigger recomposition.
Now, my requirement is to remember a list of integers.
Declared like this,
var data by rememberSaveable {
mutableStateOf(mutableListOf<Int>())
}
The list operations like clear()
, add()
, and remove()
update the data in the list but recomposition is not triggered as the list instance is still the same.
To handle this, I replaced the following list operations with these assignments.
data.clear()
, used data = arrayListOf()
data.add(ele)
, used data = mutableListOf(*data.toTypedArray(), ele)
Similarly, for remove()
tried this,
data.remove(ele)
data = mutableListOf(*data.toTypedArray())
But this is not triggering recomposition.
What is the correct alternative for remove()
?
And is there any generic to handle all list operations?
Upvotes: 10
Views: 19971
Reputation: 88072
You have two options here:
Declare your list as mutableStateListOf
. In this case you can do any operations on it, like clear()
, add()
, remove()
. See this answer how you can use it with rememberSaveable
, or move it to the view model.
val data = remember {
mutableStateListOf<Int>()
}
data.clear()
Sometimes it's more comfortable to use mutableStateOf
, in this case you can update it value like this:
var data by rememberSaveable(Unit) {
mutableStateOf(listOf<Int>())
}
data = data.toMutableList().apply {
clear()
}.toImmutableList()
Upvotes: 18