I have a repository which holds the LiveData
object and is used by both Activity
and now it's needed in JobService
(From Firebase dispatcher) through a ViewModel
.
There is answer for plain Service
over here: Observe LiveData from foreground service
But it doesn't mention how to do the same for JobService
.
You usually create an Observer object in a UI controller, such as an activity or fragment. Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes.
To answer your question, No, It is not mandatory to use LiveData always inside ViewModel, it is just an observable pattern to inform the caller about updates in data. If you have something which won't be changed frequently and can be accessed by its instance.
ViewModel allows the app's data to survive configuration changes. In this codelab, you'll learn how to integrate LiveData with the data in the ViewModel . The LiveData class is also part of the Android Architecture Components and is a data holder class that can be observed.
If you want to observe a LiveData object from something that isn't a LifecycleOwner, you can use the observeForever
method.
val data = getLiveDataFromSomewhere()
data.observeForever(object: Observer<Whatever> {
override fun onChanged(stuff: Whatever?) {
// do something with stuff
data.removeObserver(this)
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With