12

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.

Sagar
  • 23,903
  • 4
  • 62
  • 62
Akshay Chordiya
  • 4,761
  • 3
  • 40
  • 52
  • Try to play with creating custom lifecycle component https://developer.android.com/topic/libraries/architecture/lifecycle.html#implementing-lco . To start working LifecycleRegistry properly, you should call https://developer.android.com/reference/android/arch/lifecycle/LifecycleRegistry.html#handleLifecycleEvent(android.arch.lifecycle.Lifecycle.Event) method in proper order. – Sergei Vasilenko Aug 29 '17 at 08:29

1 Answers1

12

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)
    }
})
alekop
  • 2,838
  • 2
  • 29
  • 47
  • I got an exception that stated `Cannot invoke observeForever on a background thread` and used [this](https://stackoverflow.com/a/58131708/4232765) answer as a solution. – Daniel Sep 22 '20 at 10:26