How to read data and listen to changes from Room database in a Service?

steasy picture steasy · Jun 18, 2018 · Viewed 7.8k times · Source

i am storing user information in a local room database. In activities and fragments I use AndroidViewModel and LiveData to listen to changes made to the database and update the UI.

Now I want to analyze all of the past user data to give recommendations for future decisions. My recommendations change on every change to the database made by the user so I need to update my reommendations frequently while doing the same calculations over and over again.

I was thinking about starting a service on app start that listens to database changes via ViewModel and LiveData and updates my recommendations (which are also stored in the same database). But somehow a Service cannot

  1. get a ViewModel via viewModel = ViewModelProviders.of(this).get(DataViewModel.class);
  2. observe a LiveData object as it is not a LifecycleOwner.

Basically I simply need to read all entries from the database, analyze the data and update 5-10 values every time the database content changes.

How and where should I do my calculations if not in a service? Maybe I am trapped in a wrong thought and a service is not the right way to do it so any idea on how to do this is very much appreciated!

Answer

CommonsWare picture CommonsWare · Jun 19, 2018

observe a LiveData object as it is not a LifecycleOwner

Use observeForever() on the LiveData, manually unregistering via removeObserver() when appropriate (onDestroy() of the service, if not sooner).

Bear in mind that standard service limitations apply here (e.g., services run for ~1 minute on Android 8.0+ unless they are foreground services), so it may be that you need to consider other approaches anyway.