AndroidViewModel 与将应用程序上下文传递给 ViewModel
AndroidViewModel vs passing Application context to ViewModel
documentation 声明如下:
If the ViewModel needs the Application context, for example to find a system service, it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor, since Application class extends Context.
代码示例:
class MainViewModel(application: Application) : AndroidViewModel(application) {
...
}
两个问题:
- 如果我仍然需要将
Application
传递给 ViewModel 的 ctor,AndroidViewModel 如何帮助我?
- 再说一次,如果我需要通过
Application
,为什么我需要 AndroidViewModel?我可以只使用 ViewModel 并传递它 Application
.
您可以在不扩展 AndroidViewModel
的情况下编写您的自定义 ViewModel
,并且它在功能上是相同的。
唯一的区别是默认 ViewModelFactory
检查 ViewModel
是否是 AndroidViewModel
的实例并自动调用单参数构造函数向下传递 Application
上下文。
如果您要提供自己的工厂,则可以将任何您想要的内容传递给常规 ViewModel
对象,这是正确的。
但是,如果您使用的是默认工厂,the source code 显示默认工厂 仅 为您填写 Application
实例,如果您的 ViewModel扩展 AndroidViewModel
.
documentation 声明如下:
If the ViewModel needs the Application context, for example to find a system service, it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor, since Application class extends Context.
代码示例:
class MainViewModel(application: Application) : AndroidViewModel(application) {
...
}
两个问题:
- 如果我仍然需要将
Application
传递给 ViewModel 的 ctor,AndroidViewModel 如何帮助我? - 再说一次,如果我需要通过
Application
,为什么我需要 AndroidViewModel?我可以只使用 ViewModel 并传递它Application
.
您可以在不扩展 AndroidViewModel
的情况下编写您的自定义 ViewModel
,并且它在功能上是相同的。
唯一的区别是默认 ViewModelFactory
检查 ViewModel
是否是 AndroidViewModel
的实例并自动调用单参数构造函数向下传递 Application
上下文。
如果您要提供自己的工厂,则可以将任何您想要的内容传递给常规 ViewModel
对象,这是正确的。
但是,如果您使用的是默认工厂,the source code 显示默认工厂 仅 为您填写 Application
实例,如果您的 ViewModel扩展 AndroidViewModel
.