使用 PeriodicWorkRequest 使用 Room 填充数据库

Using PeriodicWorkRequest to populate a DB using Room

我一直在关注 this 关于如何使用 Room 实现数据库访问的教程。 就实现而言,AppDatabase (RoomDatabase) 是从 WordRepository (Repository) 访问的,以便抽象对数据库的访问,这是从 WordViewModel (AndroidViewModel) 访问的,而 WordViewModel (AndroidViewModel) 是从 MainActivity 访问的。

我的需求很不一样,教程没有涵盖。 我需要每小时从服务器获取数据,为此我选择了 PeriodicWorkRequest 来为我完成定期工作。
当我试图将周期性工作人员从服务器获取的数据插入到我使用的数据库中时,问题就出现了:

AppDatabase db = AppDatabase.getDatabase(context);

但是我错过了使用存储库的要点,它应该是访问数据库的唯一实体。 所以我尝试从我的工作人员访问存储库,但这意味着将它传递给工作人员没有的应用程序。 我考虑了 运行 来自 ViewModel 的 worker,并得到了它的结果,但不幸的是 PeriodicWorkRequest return 结果。

我觉得我处在一个第 22 条军规的情况下。想知道解决问题的最佳方法是什么,考虑到数据库填充是定期完成的,当用户打开应用程序时读取数据,以及当新数据从服务器添加到数据库时(因此 Observer 和 onChange 可能是一个考虑的好主意

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 对象中调用 getApplicationContext() 来获取它。然后,您可以在将参数传递给 Repository 构造函数之前将返回的对象类型转换为 Application