The way I have my app set up is that, the Service will be getting some information in the background, which needs to be acquired live by the Fragment, and then display it into a view. To do this, I put the data inside a ViewModel and let my Fragment observe the LiveData in the ViewModel.
The problem is, I am having trouble setting/changing the LiveData inside the ViewModel class from the service. It seems that ViewModel is meant to be used between Activities and Fragments, and I cannot seem to get the ViewModel inside my service in order to change the value that needs to be observed by my Fragment. Is there a way to implement this?
CodePudding user response:
You probably want to use a Repository with its own MutableLiveData field that is modified within your service. Your ViewModel will then have a MutableLiveData field that points to the Repository field, and your Fragment can observe that field.
Fragment:
...
viewModel.myData.observe(viewLifecycleOwner) { myData ->
// handle new data observed
}
...
ViewModel:
// Need to clear repo reference in [onCleared] to avoid resource leaks
private var _myData: MutableLiveData<MyData>? = myRepo.myData
val myData: MutableLiveData<MyData> = _myData
...
override fun onCleared() {
super.onCleared()
_myData = null
}
Repository:
val myData = MutableLiveData<MyData>() // or whatever source (Room, etc.)
Service:
...
Repository.getInstance().myData.postValue(/* some new info */)
...