Ahmad Jamal Mughal
Ahmad Jamal Mughal

Reputation: 89

Cannot observe LiveData<MutableList<T>> from ViewModel in my fragment

MyFragment.kt:

viewModel.studentsTemp.observe(this, Observer {
    adapter.submitList(it)
})

MyViewModel.kt

private var _studentsTemp = MutableLiveData<MutableList<Student>>()
val studentsTemp: LiveData<MutableList<Student>> get() = _studentsTemp
init {
        _studentsTemp.value = mutableListOf<Student>()
}

Observer is only being called when the application starts i.e. when ViewModel is created i.e. when init block runs in View Model.

Upvotes: 3

Views: 1221

Answers (1)

Francesc
Francesc

Reputation: 29360

You have a MutableList in your MutableLiveData. Note that if you add or remove items from your MutableList this will NOT trigger the observer. To trigger the observer you have to update the LiveData variable.

So this will not trigger the observer

studentsTemp.value?.add(student)

but this will

studentsTemp.value = studentsTemp.value?.add(student) ?: mutableListOf(studen)

Upvotes: 7

Related Questions