kotlinarraylistmutablelivedata

How to add items to MutableLiveData arraylist?


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


Solution

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