3

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.

Buddy Christ
  • 1,364
  • 8
  • 22

1 Answers1

7

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)
Francesc
  • 25,014
  • 10
  • 66
  • 84
  • 1
    Thank you so so so much for bringing my attention to it. I just added the line `_studentsTemp.value = _studentsTemp.value` after the add function and it triggered the observer. – Ahmad Jamal Mughal Apr 07 '20 at 19:27