7

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.

  1. Instead of data.clear(), used data = arrayListOf()
  2. Instead of 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?

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121

1 Answers1

13

You have two options here:

  1. 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()
    
  2. 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()
    
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
  • Getting this error, `Type 'TypeVariable(T)' has no method 'getValue(Nothing?, KProperty<*>)' and thus it cannot serve as a delegate`. I have these 2 imports - `import androidx.compose.runtime.setValue` and `import androidx.compose.runtime.getValue`. Not sure, what I am missing. – Abhimanyu Nov 11 '21 at 18:16
  • Yup, missed that. Was trying with delegation. Now I ended up in [this error](https://stackoverflow.com/questions/68885154/using-remembersaveable-with-mutablestatelistof). For a simple list of integers, I have to manually create a custom saver? – Abhimanyu Nov 11 '21 at 18:29
  • 1
    @Abhimanyu Looks like you've found [this answer](https://stackoverflow.com/a/68887484/3585796). I've added a link to it to this answer too – Phil Dukhov Nov 11 '21 at 18:48