Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observe LiveData from JobService

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.

like image 273
Akshay Chordiya Avatar asked Aug 29 '17 07:08

Akshay Chordiya


People also ask

How do you observe a LiveData?

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.

Can I use LiveData without ViewModel?

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.

Can we observe in ViewModel?

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.


1 Answers

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)
    }
})
like image 153
alekop Avatar answered Sep 20 '22 14:09

alekop