我在 Android 应用程序中使用 Room 数据库,需要创建
context
类的实例。我想在 ViewModel 中访问数据库,但只能在可组合项或活动中获取上下文,因此我在 MainActivity 中创建 ViewModel,并将 Application
(Application
继承 Context
)类传递给它来初始化数据库。然后我将 ViewModel 传递给顶级可组合项。
它工作得很好,但是Android指南说应该避免这种情况:
Strongly recommended:
ViewModels shouldn't hold a reference to any Lifecycle-related type.
Don't pass Activity, Fragment, Context or Resources as a dependency.
If something needs a Context in the ViewModel, you should strongly evaluate if that is in the right layer.
和
Recommended:
Use the ViewModel class, not AndroidViewModel.
The Application class shouldn't be used in the ViewModel. Instead, move the dependency to the UI or the data layer.
那么我应该将数据库依赖移到哪里?
您可以在调用 onCreate 函数之前创建一个稍后的初始化变量,然后在调用覆盖 onCreate 函数之后将值分配给该变量,这使您能够在应用程序中全局使用该函数,然后将视图模型迁移到主活动之外,一个单独的文件