Search code examples
androidkotlinandroid-viewmodel

How to add data to List in MutableLiveData?


I want to add an item to a List of MutableLiveData in ViewModel.

List is read-only because it was initialized with listOf().

But in a specific case I want to add an item.

To do this, I used toMutableList() to type cast, but as a result of debugging, there was no change in the List of LiveData.

How can I apply data to a List of LiveData?

class WriteRoutineViewModel : ViewModel() {
    private var _items: MutableLiveData<List<RoutineModel>> = MutableLiveData(listOf())

    val items: LiveData<List<RoutineModel>> = _items

    fun addRoutine(workout: String) {
        val item = RoutineModel(workout, "TEST")
        _items.value?.toMutableList()?.add(item) // nothing change
    }
}

Solution

  • _items.value?.toMutableList() creates a new list instance, so you're not adding elements to the list in the LiveData.

    Even if you did manage to add elements to the actual list object in the LiveData (by using some dirty cast), it would probably not trigger a change event in the LiveData, so subscribers wouldn't be notified of the new value.

    What you want is to actually assign a new list to the MutableLiveData:

    _items.value = _items.value?.plus(item) ?: listOf(item)
    

    (if the current list in the LiveData is null, a new list will be assigned with just the new item)