I observe viewmodel livedata:
var result: LiveData<List<LocationEntity>> = MutableLiveData()
in fragment subscribeUi() is called to observe:
override fun onResume() {
super.onResume()
subscribeUi() // or inside onViewCreated
}
private fun subscribeUi() {
viewModel.result.observe(viewLifecycleOwner) { routes ->
if (routes != null) listAdapter.setData(routes)
}
}
It works fine when fragment view is created or resumed, but if I call update function in viewmodel which queries room database for another list the fragment observer is NOT triggered! Room database returns Flow (converted to LiveData) and works fine with LiveData. Any changes in database (insert, delete, update) are reflected in fragment’s recycler list. I use shared viewmodel in fragment:
private val viewModel: MainViewModel by activityViewModels()
...
fun updateResults(id: Long) {
viewModelScope.launch {
result = repository.getRoutes(id).asLiveData()
}
}
I guess this happens because LiveData is returned, not MutableLiveData. As workaround I call observer function after update function and it works.
viewModel.updateResults(id)
subscribeUi()
But is there a better way? Not calling observer each time? Could someone explain what happens?