Peter
Peter

Reputation: 1159

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 class, but it required my service class to be a lifecycleowner.

am stuck with how to make my service class observer to the changes in a live data

Any help will be good!!

Upvotes: 4

Views: 6316

Answers (1)

Xid
Xid

Reputation: 4951

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:

override fun onStart() {
   super.onStart()

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

override fun onStop() {
    unbindService(myServiceConnection)
    super.onStop()
}

Read on bound services here

Then, in the service

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

    return serviceBinder
}

override fun onRebind(intent: Intent?) {
    liveData.observeForever(observer)

    super.onRebind(intent)
}
  1. Remove LiveData observer in onUnbind(Intent) (App is in background)
override fun onUnbind(intent: Intent?): Boolean {
    liveData.removeObserver(observer)
    return true
}

Upvotes: 13

Related Questions