Home > Mobile >  correct way to handle mutable state of list of data in jetpack compose
correct way to handle mutable state of list of data in jetpack compose

Time:11-12

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?

CodePudding user response:

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()
    }
    
  • Related