Room - 何时初始化数据库以及如何通过应用程序生命周期访问它

Room - when to initialize database and how to access it through app lifecycle

我正在尝试设置 Room 作为一种简化对 SQLite 数据库的访问的方法。我已经写了一些代码,但我不能 运行 它,因为应用抛出以下异常:

Cannot access database on the main thread since it may potentially lock the UI for a long period of time

我做了一些研究,我发现 .allowMainThreadQueries()databaseBuilder 中,这在我看来是糟糕的解决方案,因为它就像屏蔽​​错误消息,而不是修复真正的原因。

那么,最佳做法是什么?什么时候(在应用程序生命周期中)我应该创建我的数据库以及我应该在哪里存储它以便我可以从任何我想要的 Activity 访问它?

When (in app lifecycle) should I create my database

在第一次访问时延迟创建 RoomDatabase,就像直接使用 SQLiteOpenHelper 时一样。

where should I store it

单例将是一个典型的模式,就像您直接使用 SQLiteOpenHelper 时一样。

这些问题都与错误消息无关。这是在后台线程上访问数据库的问题,就像直接使用 SQLiteOpenHelper 时一样。对于 @Query 方法,您可以选择让方法 return 成为 LiveData 或 RxJava 类型(例如,Flowable),在这种情况下,Room 会负责在后台线程上工作。对于其他操作(例如 @Insert),您有责任自己在后台线程上调用这些方法(ThreadAsyncTaskThreadPoolExecutorIntentServiceJobIntentService,等等)。