一、ViewModel使用
如图1,ViewModel使用很简单,只用将类继承ViewModel类即可

如图2,在Activity里面只要使用ViewModelProvider get方法就可以得到对应的ViewModel实例

二、 ViewModel的作用
1、当Activity、Fragment因为配置项发生改变重新生成时,界面数据就会丢失,尽管可以使用onSaveInstanceState()保存数据,但此方法仅适合可以序列化再反序列化的少量数据,而不适合数量可能较大的数据,如用户列表或位图。而ViewModel可以很好地处理该情况下数据地保存。
2、当不同Fragment想公用一套Activity的数据时,ViewModel可以很好地支持这种情况。
3、ViewModel简化了Activity、Fragment的处理逻辑,使整个框架更加优美。
三、 ViewModel的原理
ViewModel为什么会产生如上所说的作用呢,下面我们就从源码开始进行分析。如下,ViewModelProvider构造函数传入的为ViewModelStoreOwner实例。

这个实例是什么呢,如图4其实就是一个接口,里面只有一个方法就是获取ViewModelStore类的实例

如图5,就是ViewModel的容器

下面来看看ViewModel的实例怎么产生的吧,如图6,ViewModel实例先从viewModelStore缓存中去取,如果取不到再去新建,现在只要弄清viewModelStore

从哪里来,那么所有的谜团就解开了。ComponentActivity里面实现了ViewModelStoreOwner接口,可以看出mViewModelStore首先会从getLastNonConfigurationInstance配置类中去获取,顾名思义,这个类是和配置无关的类。

关于这个变量的赋值是发生在Activity attach里面。至于赋值流程,我还未搞清,如大牛们有清楚的,请在评论区指教

网友评论