0

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.

paul-shuvo
  • 1,874
  • 4
  • 33
  • 37
Nitin Verma
  • 485
  • 4
  • 19

1 Answers1

0

observeForever can be used in the ViewModel, but be sure to remove the observer in the onCleared() callback.

To do so, create your own Observer:

 var customObserver: Observer<Results> = Observer { results ->
        results ?: return@Observer
        viewModel.showResults(results)
    }

Pass this observer in when you observeForever:

 contestLiveData.observeForever(customObserver) 

Remove the observer in onCleared():

contestLiveData.removeObserver(customObserver)
Daniel Rust
  • 539
  • 1
  • 4
  • 15