AndroidViewModel与ViewModel [英] AndroidViewModel vs ViewModel
问题描述
随着Android Architecture Components库的引入,引入了几个新类,包括AndroidViewModel
和ViewModel
.但是,我很难弄清楚这两个类之间的区别. 文档简要地描述了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
我很欣赏简短,但这到底意味着什么?何时应该选择在ViewModel
上使用AndroidViewModel
,反之亦然?
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屋!