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.
- Instead of
data.clear(), useddata = arrayListOf() - Instead of
data.add(ele), useddata = 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?
CodePudding user response:
You have two options here:
Declare your list as
mutableStateListOf. In this case you can do any operations on it, likeclear(),add(),remove(). See this answer how you can use it withrememberSaveable, 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() }
