I've been following this tutorial on how to implement database access using Room. As far as the implementation is explained the AppDatabase (RoomDatabase) is accessed from the WordRepository (Repository) in order to abstract the access to the Database, which is accessed from WordViewModel (AndroidViewModel) which is accessed from the MainActivity.
My needs are quite different and are not covered by the tutorial.
I will need to perform hourly fetches of data from a server, for which I chose a PeriodicWorkRequest to do the periodic work for me.
The problem emerges when I am trying to insert data fetched from the server by the periodic worker into the DB, for which I use:
AppDatabase db = AppDatabase.getDatabase(context);
But then I am missing the point of using the Repository, which should be the only entity accessing the DB. So I tried accessing the Repository from my worker, but that means passing it Application, which the worker does not have. I thought about running the worker from the ViewModel, and getting its result, but unfortunately PeriodicWorkRequest cannot return a result.
I feel like i'm in a catch-22 situation here. Wondering what is the best way to solve the problem, considering Database populating is done periodically and reading the data is done when the user opens the app, and when new data is added from the server into the DB (thus Observer and onChange are probably a good idea to take into account
But then I am missing the point of using the Repository, which should be the only entity accessing the DB. So I tried accessing the Repository from my worker, but that means passing it Application, which the worker does not have.
Worker does have Application! you can get it by calling getApplicationContext()
within Worker object. Then you can typecast the returned object to Application
before passing the argument to the Repository constructor.