Home > Enterprise >  What is the difference between mutableStateOf and mutableStateListOf?
What is the difference between mutableStateOf and mutableStateListOf?

Time:01-07

While working with a ViewModel and a List stored in there, I usually followed this approach:

var characteristics by mutableStateOf(listOf<Characteristic>())

Then, I could assign data to the List or modify it, and the UI would recompose properly:

characteristics = issuesRepository.getCharacteristics()
characteristics = characteristics.plus(newCharacteristic)

However, I recently stumbled across several approaches containing the keyword mutableStateListOf(), and it then seems to be a common practice to split a List into two separate variables, like this:

private val _characteristic = mutableStateListOf<Characteristic>()
val characteristic: List<Characteristic> = _characteristic

How do these approaches differ, and is one of those considered best-practice or as a cleaner approach?

CodePudding user response:

Using mutableStateOf you are creating an observable object. So, the recomposition will happen just if you assign a new instance to this state. Let's say that you want that recomposition happens after add a new item to the list. In this case, you need to create a copy of this list, add the elemento to this copied list, and then assign the copied list to the state.

The mutableStateListOf creates an observable list. All operations you've done in this list (add, remove, update) will cause a recomposition.

  • Related