Home > Software design >  How to add items to MutableLiveData arraylist?
How to add items to MutableLiveData arraylist?

Time:06-30

I have a MainViewModelwith the code:

private val locationList: MutableLiveData<ArrayList<Location>> = MutableLiveData()
fun getLocationList(): MutableLiveData<ArrayList<Location>> = locationList

and a fragment where I am trying to add values to the arraylist, but I don't know how:

mainViewModel.getLocationList.value = arrayListof(location) //creates always a new list

Maybe someone can help me. Thank you

CodePudding user response:

mainViewModel.getLocationList.value?.add(newLocation)
mainViewModel.getLocationList.value = mainViewModel.getLocationList.value // notify observers

CodePudding user response:

Your view model should look like this:

private val _locationList: MutableLiveData<ArrayList<Location>> = MutableLiveData()
val locationList: LiveData<ArrayList<Location>> get() = _locationList

fun setLocationList(newLocationList: ArrayList<Location>) {
    _locationList.value = newLocationList
}

And now in your fragment to set list to the mutable live data use this code:

mainViewModel.setLocationList(list)

And you can observe locationList LiveData or use it's value with locationList.value

To add items to the existing list you can use this function:

fun addItemToLocationList(location: Location) {
    val list = ArrayList(_locationList.value)
    list.add(location)
    _locationList.value = list
}
  • Related