AndroidViewModel 与 ViewModel [英] AndroidViewModel vs ViewModel

查看:153
本文介绍了AndroidViewModel 与 ViewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着 Android 架构组件库的引入,引入了几个新类,包括 AndroidViewModelViewModel.但是,我无法弄清楚这两个类之间的区别.文档 简洁地将 AndroidViewModel 描述为如下:

With the introduction of the Android Architecture Components library, several new classes were introduced, including AndroidViewModel and ViewModel. However, I'm having trouble figuring out the difference between these two classes. The documentation succinctly describes AndroidViewModel as follows:

应用上下文感知ViewModel

我很欣赏简洁,但这到底意味着什么?我们什么时候应该选择使用 AndroidViewModel 而不是 ViewModel,反之亦然?

I appreciate the brevity, but what exactly does this imply? When should we choose to use AndroidViewModel over ViewModel and vice-versa?

推荐答案

AndroidViewModel 提供应用上下文

如果您需要在 Viewmodel 中使用上下文,您应该使用 AndroidViewModel (AVM),因为它包含应用程序上下文.要检索上下文调用 getApplication(),否则使用常规 ViewModel (VM).

AndroidViewModel provides Application context

If you need to use context inside your Viewmodel you should use AndroidViewModel (AVM), because it contains the application context. To retrieve the context call getApplication(), otherwise use the regular ViewModel (VM).

AndroidViewModel 具有应用程序上下文.我们都知道拥有静态上下文实例是邪恶的,因为它会导致内存泄漏!!但是,拥有静态应用程序实例并不像你想象的那么糟糕,因为只有一个正在运行的应用程序中的应用程序实例.

AndroidViewModel has application context. We all know having static context instance is evil as it can cause memory leaks!! However, having static Application instance is not as bad as you might think because there is only one Application instance in the running application.

因此,在特定类中使用和拥有 Application 实例通常不是问题.但是,如果一个 Application 实例引用它们,就会因为引用循环问题而出问题.

Therefore, using and having Application instance in a specific class is not a problem in general. But, if an Application instance references them, it is a problem because of the reference cycle problem.

另见关于应用程序实例

AVM 提供了对单元测试有问题的应用程序上下文.单元测试不应处理任何 Android 生命周期,例如上下文.

AVM provides application context which is problematic for unit testing. Unit tests should not deal with any of the Android lifecycle, such as context.

这篇关于AndroidViewModel 与 ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆