Skip to content Skip to sidebar Skip to footer

How To Observe A Live Data Inside Service Class

I want to insert some records which I get from the API to my database, I am using a service class to do this process, I was trying to use this concept of live data inside service c

Solution 1:

If your service should not be affected by activity lifecycle (onStop(), onStart() etc) then you can use LiveData<T>.observeForever(Observer<T>) method. Like so,

val observer = Observer<YourDataType> { data ->
    //Live data value has changed
}

liveData.observeForever(observer)

To stop observing you will have to call LiveData.removeObserver(Observer<T>). Like so:

liveData.removeObserver(observer)

If you need to stop observing when the application is in the background, you can bind your service in the calling activity in the onStart() method of the activity and unbind your service in the onStop() method. Like so:

overridefunonStart() {
   super.onStart()

   val serviceIntent = Intent(this, myService::class.java)
   bindService(serviceIntent, myServiceConnection, Context.BIND_AUTO_CREATE)
}

overridefunonStop() {
    unbindService(myServiceConnection)
    super.onStop()
}

Read on bound serviceshere

Then, in the service

  1. override onBind(Intent) and onRebind(Intent) method and start observing the LiveData (App is in foreground)
overridefunonBind(intent: Intent?): IBinder? {
    liveData.observeForever(observer)

    return serviceBinder
}

overridefunonRebind(intent: Intent?) {
    liveData.observeForever(observer)

    super.onRebind(intent)
}
  1. Remove LiveData observer in onUnbind(Intent) (App is in background)
overridefunonUnbind(intent: Intent?): Boolean {
    liveData.removeObserver(observer)
    returntrue
}

Post a Comment for "How To Observe A Live Data Inside Service Class"