I am following the MVVM pattern in my android app. Here are the files that I will be talking about:
PresentContestsFragment
PresentContestsViewModel
here's my code of view model:
private val _contests = MutableLiveData<List<ContestsShortInfoModel>>()
val contests:LiveData<List<ContestsShortInfoModel>>
get() = _contests
fun getContests() {
viewModelScope.launch{
val contestLiveData = repository.getLiveContests()
contestLiveData.observeForever {
_contests.value = it
}
}
}
Here's my code of fragment class
In it's onActivityCreated I call viewModel.getContests() and then bindUI()
private fun bindUI() {
viewModel.contests.observe(this, Observer { list ->
list?.let{
// show this list in UI
}
})
}
everything is working good and my UI is updating. I want to ask whether it's ok to call observeForever in the view model. If not how should I remove the observer?
If you have a better method to do it, please tell that also.
Remember that when I call getLiveContests of repository then in repo, I check if there is a need to get fresh data from the internet or not. whatever the case, I return LiveData from room db. If new data was fetched, it is saved to the room and as I have returned LiveData so I am getting updates in the UI also.