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.
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)