ViewModel 是什么?
ViewModel 是 Jetpack 的一部分。
ViewModel 类旨在以注重生命周期的方式存储和管理界面相关的数据。ViewModel 类让数据可在发生屏幕旋转等配置更改后继续留存。
摘自官方文档:ViewModel 概览

ViewModel 相关问题是高频面试题。主要源于它是 MVVM 架构模式的重要组件,并且它可以在因配置更改导致页面销毁重建时依然保留 ViewModel 实例。

看看 ViewModel 的生命周期

ViewModel 只有在正常 Activity finish 时才会被清除。

问题来了:

为什么Activity旋转屏幕后ViewModel可以恢复数据
ViewModel 的实例缓存到哪儿了
什么时候 ViewModel#onCleared() 会被调用
在解决这三个问题之前,回顾下 ViewModel 的用法特性

基本使用
MainRepository

class MainRepository {suspend fun getNameList(): List<String> {return withContext(Dispatchers.IO) {listOf("张三", "李四")}}
}

MainViewModel

class MainViewModel: ViewModel() {private val nameList = MutableLiveData<List<String>>()val nameListResult: LiveData<List<String>> = nameListprivate val mainRepository = MainRepository()fun getNames() {viewModelScope.launch {nameList.value = mainRepository.getNameList()}}
}

MainActivity

class MainActivity : AppCompatActivity() {// 创建 ViewModel 方式 1// 通过 kotlin 委托特性创建 ViewModel// 需添加依赖 implementation 'androidx.activity:activity-ktx:1.2.3'// viewModels() 内部也是通过 创建 ViewModel 方式 2 来创建的 ViewModelprivate val mainViewModel: MainViewModel by viewModels()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate  (savedInstanceState)setContentView(R.layout.activity_main)// 创建 ViewModel 方式 2val mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)mainViewModel.nameListResult.observe(this, {Log.i("MainActivity", "mainViewModel: nameListResult: $it")Log.i("MainActivity", "MainActivity: ${this@MainActivity} mainViewModel: $mainViewModel  mainViewModel.nameListResult: ${mainViewModel.nameListResult}")})mainViewModel.getNames()}
}

LiveData 会在后续文章中进行介绍

测试步骤:打开app -> 正常看到日志

18:03:02.575 : mainViewModel: nameListResult: [张三, 李四]
18:03:02.575 : com.yqy.myapplication.MainActivity@7ffa77 mainViewModel: com.yqy.myapplication.MainViewModel@29c0057  mainViewModel.nameListResult: androidx.lifecycle.MutableLiveData@ed0d744

接着测试步骤:打开设置更换系统语言 -> 切换到当前app所在的任务 再看日志

18:03:59.622 : mainViewModel: nameListResult: [张三, 李四]
18:03:59.622 : com.yqy.myapplication.MainActivity@49a4455 mainViewModel: com.yqy.myapplication.MainViewModel@29c0057  mainViewModel.nameListResult: androidx.lifecycle.MutableLiveData@ed0d744

神奇!MainActivity 被重建了,而 ViewModel 的实例没有变,并且 ViewModel 对象里的 LiveData 对象实例也没变。
这就是 ViewModel 的特性。

ViewModel 出现之前,Activity 可以使用 onSaveInstanceState() 方法保存,然后从 onCreate() 中的 Bundle 恢复数据,但此方法仅适合可以序列化再反序列化的少量数据(IPC 对 Bundle 有 1M 的限制),而不适合数量可能较大的数据,如用户信息列表或位图。
ViewModel 的出现完美解决这个问题。

我们先看看 ViewModel 怎么创建的:
通过上面的实例代码,最终 ViewModel 的创建方法是

val mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)

创建 ViewModelProvider 对象并传入了 this 参数,然后通过 ViewModelProvider#get 方法,传入 MainViewModel 的 class 类型,然后拿到了 mainViewModel 实例。

ViewModelProvider 的构造方法

public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {// 获取 owner 对象的 ViewModelStore 对象this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory(): NewInstanceFactory.getInstance());}

ViewModelProvider 构造方法的参数类型是 ViewModelStoreOwner ?ViewModelStoreOwner 是什么?我们明明传入的 MainActivity 对象呀!
看看 MainActivity 的父类们发现

public class ComponentActivity extends androidx.core.app.ComponentActivity implements...// 实现了 ViewModelStoreOwner 接口ViewModelStoreOwner,...{private ViewModelStore mViewModelStore;// 重写了 ViewModelStoreOwner 接口的唯一的方法 getViewModelStore()@NonNull@Overridepublic ViewModelStore getViewModelStore() {if (getApplication() == null) {throw new IllegalStateException("Your activity is not yet attached to the "+ "Application instance. You can't request ViewModel before onCreate call.");}ensureViewModelStore();return mViewModelStore;}

ComponentActivity 类实现了 ViewModelStoreOwner 接口。
奥 ~~ 刚刚的问题解决了。

再看看刚刚的 ViewModelProvider 构造方法里调用了 this(ViewModelStore, Factory),将 ComponentActivity#getViewModelStore 返回的 ViewModelStore 实例传了进去,并缓存到 ViewModelProvider 中

public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {mFactory = factory;// 缓存 ViewModelStore 对象mViewModelStore = store;}

接着看 ViewModelProvider#get 方法做了什么

@MainThreadpublic <T extends ViewModel> T get(@NonNull Class<T> modelClass) {String canonicalName = modelClass.getCanonicalName();if (canonicalName == null) {throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");}return get(DEFAULT_KEY + ":" + canonicalName, modelClass);}

获取 ViewModel 的 CanonicalName , 调用了另一个 get 方法

@MainThreadpublic <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {// 从 mViewModelStore 缓存中尝试获取ViewModel viewModel = mViewModelStore.get(key);// 命中缓存if (modelClass.isInstance(viewModel)) {if (mFactory instanceof OnRequeryFactory) {((OnRequeryFactory) mFactory).onRequery(viewModel);}// 返回缓存的 ViewModel 对象return (T) viewModel;} else {//noinspection StatementWithEmptyBodyif (viewModel != null) {// TODO: log a warning.}}// 使用工厂模式创建 ViewModel 实例if (mFactory instanceof KeyedFactory) {viewModel = ((KeyedFactory) mFactory).create(key, modelClass);} else {viewModel = mFactory.create(modelClass);}// 将创建的 ViewModel 实例放进 mViewModelStore 缓存中mViewModelStore.put(key, viewModel);// 返回新创建的 ViewModel 实例return (T) viewModel;}

mViewModelStore 是啥?通过 ViewModelProvider 的构造方法知道 mViewModelStore 其实是我们 Activity 里的 mViewModelStore 对象,它在 ComponentActivity 中被声明。
看到了 put 方法,不难猜它内部用了 Map 结构。

public class ViewModelStore {// 果不其然,内部有一个 HashMapprivate final HashMap<String, ViewModel> mMap = new HashMap<>();final void put(String key, ViewModel viewModel) {ViewModel oldViewModel = mMap.put(key, viewModel);if (oldViewModel != null) {oldViewModel.onCleared();}}// 通过 key 获取 ViewModel 对象final ViewModel get(String key) {return mMap.get(key);}Set<String> keys() {return new HashSet<>(mMap.keySet());}/***  Clears internal storage and notifies ViewModels that they are no longer used.*/public final void clear() {for (ViewModel vm : mMap.values()) {vm.clear();}mMap.clear();}
}

到这儿正常情况下 ViewModel 的创建流程看完了,似乎没有解决任何问题~
简单总结:ViewModel 对象存在了 ComponentActivity 的 mViewModelStore 对象中。
第二个问题解决了:ViewModel 的实例缓存到哪儿了

转换思路 mViewModelStore 出现频率这么高,何不看看它是什么时候被创建的呢?

记不记得刚才看 ViewModelProvider 的构造方法时 ,获取 ViewModelStore 对象时,实际调用了 MainActivity#getViewModelStore() ,而 getViewModelStore() 实现在 MainActivity 的父类 ComponentActivity 中。

// ComponentActivity#getViewModelStore()@Overridepublic ViewModelStore getViewModelStore() {if (getApplication() == null) {throw new IllegalStateException("Your activity is not yet attached to the "+ "Application instance. You can't request ViewModel before onCreate call.");}ensureViewModelStore();return mViewModelStore;}

在返回 mViewModelStore 对象之前调用了 ensureViewModelStore()

void ensureViewModelStore() {if (mViewModelStore == null) {NonConfigurationInstances nc =(NonConfigurationInstances) getLastNonConfigurationInstance();if (nc != null) {// Restore the ViewModelStore from NonConfigurationInstancesmViewModelStore = nc.viewModelStore;}if (mViewModelStore == null) {mViewModelStore = new ViewModelStore();}}}

当 mViewModelStore == null 调用了 getLastNonConfigurationInstance() 获取 NonConfigurationInstances 对象 nc,当 nc != null 时将 mViewModelStore 赋值为 nc.viewModelStore,最终 viewModelStore == null 时,才会创建 ViewModelStore 实例。
不难发现,之前创建的 viewModelStore 对象被缓存在 NonConfigurationInstances 中

// 它是 ComponentActivity 的静态内部类static final class NonConfigurationInstances {Object custom;// 果然在这儿ViewModelStore viewModelStore;}

NonConfigurationInstances 对象通过 getLastNonConfigurationInstance() 来获取的

// Activity#getLastNonConfigurationInstance/*** Retrieve the non-configuration instance data that was previously* returned by {@link #onRetainNonConfigurationInstance()}.  This will* be available from the initial {@link #onCreate} and* {@link #onStart} calls to the new instance, allowing you to extract* any useful dynamic state from the previous instance.** <p>Note that the data you retrieve here should <em>only</em> be used* as an optimization for handling configuration changes.  You should always* be able to handle getting a null pointer back, and an activity must* still be able to restore itself to its previous state (through the* normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this* function returns null.** <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API* {@link Fragment#setRetainInstance(boolean)} instead; this is also* available on older platforms through the Android support libraries.** @return the object previously returned by {@link #onRetainNonConfigurationInstance()}*/@Nullablepublic Object getLastNonConfigurationInstance() {return mLastNonConfigurationInstances != null? mLastNonConfigurationInstances.activity : null;}

好长一段注释,大概意思有几点:

onRetainNonConfigurationInstance 方法和 getLastNonConfigurationInstance 是成对出现的,跟 **onSaveInstanceState(Bundle)**机制类似,只不过它是仅用作处理配置更改的优化。
返回的是 onRetainNonConfigurationInstance 返回的对象
onRetainNonConfigurationInstance 和 getLastNonConfigurationInstance 的调用时机在本篇文章不做赘述,后续文章会进行解释。

看看 onRetainNonConfigurationInstance 方法

/*** 保留所有适当的非配置状态*/@Override@Nullable@SuppressWarnings("deprecation")public final Object onRetainNonConfigurationInstance() {// Maintain backward compatibility.Object custom = onRetainCustomNonConfigurationInstance();ViewModelStore viewModelStore = mViewModelStore;// 若 viewModelStore 为空,则尝试从 getLastNonConfigurationInstance() 中获取if (viewModelStore == null) {// No one called getViewModelStore(), so see if there was an existing// ViewModelStore from our last NonConfigurationInstanceNonConfigurationInstances nc =(NonConfigurationInstances) getLastNonConfigurationInstance();if (nc != null) {viewModelStore = nc.viewModelStore;}}// 依然为空,说明没有需要缓存的,则返回 nullif (viewModelStore == null && custom == null) {return null;}// 创建 NonConfigurationInstances 对象,并赋值 viewModelStoreNonConfigurationInstances nci = new NonConfigurationInstances();nci.custom = custom;nci.viewModelStore = viewModelStore;return nci;}

到这儿我们大概明白了,Activity 在因配置更改而销毁重建过程中会先调用 onRetainNonConfigurationInstance 保存 viewModelStore 实例。
在重建后可以通过 getLastNonConfigurationInstance 方法获取之前的 viewModelStore 实例。

现在解决了第一个问题:为什么Activity旋转屏幕后ViewModel可以恢复数据

再看第三个问题:什么时候 ViewModel#onCleared() 会被调用

public abstract class ViewModel {protected void onCleared() {}@MainThreadfinal void clear() {mCleared = true;// Since clear() is final, this method is still called on mock objects// and in those cases, mBagOfTags is null. It'll always be empty though// because setTagIfAbsent and getTag are not final so we can skip// clearing itif (mBagOfTags != null) {synchronized (mBagOfTags) {for (Object value : mBagOfTags.values()) {// see comment for the similar call in setTagIfAbsentcloseWithRuntimeException(value);}}}onCleared();}
}

onCleared() 方法被 clear() 调用了。
刚才看 ViewModelStore 源码时好像是调用了 clear() ,回顾一下:

public class ViewModelStore {private final HashMap<String, ViewModel> mMap = new HashMap<>();final void put(String key, ViewModel viewModel) {ViewModel oldViewModel = mMap.put(key, viewModel);if (oldViewModel != null) {oldViewModel.onCleared();}}final ViewModel get(String key) {return mMap.get(key);}Set<String> keys() {return new HashSet<>(mMap.keySet());}/***  Clears internal storage and notifies ViewModels that they are no longer used.*/public final void clear() {for (ViewModel vm : mMap.values()) {vm.clear();}mMap.clear();}
}

在 ViewModelStore 的 clear() 中,遍历 mMap 并调用 ViewModel 对象的 clear() ,
再看 ViewModelStore 的 clear() 什么时候被调用的:

// ComponentActivity 的构造方法public ComponentActivity() {... getLifecycle().addObserver(new LifecycleEventObserver() {@Overridepublic void onStateChanged(@NonNull LifecycleOwner source,@NonNull Lifecycle.Event event) {if (event == Lifecycle.Event.ON_DESTROY) {// Clear out the available contextmContextAwareHelper.clearAvailableContext();// And clear the ViewModelStoreif (!isChangingConfigurations()) {getViewModelStore().clear();}}}});...}

观察当前 activity 生命周期,当 Lifecycle.Event == Lifecycle.Event.ON_DESTROY,并且 isChangingConfigurations() 返回 false 时才会调用 ViewModelStore#clear 。

 // Activity#isChangingConfigurations()/*** Check to see whether this activity is in the process of being destroyed in order to be* recreated with a new configuration. This is often used in* {@link #onStop} to determine whether the state needs to be cleaned up or will be passed* on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.** @return If the activity is being torn down in order to be recreated with a new configuration,* returns true; else returns false.*/public boolean isChangingConfigurations() {return mChangingConfigurations;}

isChangingConfigurations 用来检测当前的 Activity 是否因为 Configuration 的改变被销毁了, 配置改变返回 true,非配置改变返回 false。

总结,在 activity 销毁时,判断如果是非配置改变导致的销毁, getViewModelStore().clear() 才会被调用。

第三个问题:什么时候 ViewModel#onCleared() 会被调用 解决!

————————————————
版权声明:本文为CSDN博主「Android翻山之路」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u012885461/article/details/118073987

ViewModel 必知的几个问题相关推荐

  1. 程序员必知8大排序3大查找(三)

    前两篇 <程序员必知8大排序3大查找(一)> <程序员必知8大排序3大查找(二)> 三种查找算法:顺序查找,二分法查找(折半查找),分块查找,散列表(以后谈) 一.顺序查找的基 ...

  2. Android 开发者必知的开发资源

    英文原文:Bongzimo  翻译: ImportNew-黄小非 译文链接:http://www.importnew.com/3988.html Android 开发者必知的开发资源 随着Androi ...

  3. Python工程师求职必知的经典面试题

    最近几年,学习Python语言的同学越来越多,学成之后大家对于后期的面试都遇到了很多难题,小编这次为大家整理了一份关于Python工程师求职必知的经典面试题!希望能够帮助到正在找Python工作的同学 ...

  4. servlet必知细节(三)-- DefaultServlet

    servlet必知细节(三)-- DefaultServlet 缺省servlet:org.apache.catalina.servlets.DefaultServlet,作用是处理其他servlet ...

  5. servlet必知细节(二)--servlet执行过程

    servlet必知细节(二)--servlet执行过程 我们知道,servlet没有main函数,那么,servlet是怎么调用的呢? 实际上,servlet 是由tomcat调用的,tomcat调用 ...

  6. servlet必知细节(一)

    servlet必知细节(一) 今天复习了一下servlet,有过一些编程经验后,与最初学习servlet相比,对servlet理解的角度不同了,最初只是学习了如何写一个servlet,api怎么用,现 ...

  7. 关于 Python3.9,看这张 16 岁高中生做的「新特性必知图」就够了

    金磊 发自 凹非寺 量子位 报道 | 公众号 QbitAI Python3.9,「千呼万唤始出来」. 先来速看下此次发布版本的重点. 新语法特性: PEP 584,为 dict 增加合并运算符. PE ...

  8. 京东运营插件_技术中台产品经理必知的那些易混词儿(1):组件、套件、 中间件、插件……...

    编辑导语:在产品经理做技术中台时,有很多需要知道的专有名词概念:比如:组件.套件.中间件.插件等等,本文作者对此进行了解释和梳理,便于产品经理可以快速理解技术中台产品的逻辑和思维,我们一起来看一下. ...

  9. 管理员必知:服务器基准测试方法与误区

    http://www.itwaka.com/ 在上一篇文章<管理员必知:服务器基准测试六大步骤>中,我们介绍了服务器性能衡量的标准以及进行服务器性能测试所必须的六大步骤.所有的准备工作都做 ...

最新文章

  1. 一个预告|恭喜斯科特·阿伦森获得2021年ACM计算奖
  2. 论坛项目(docker模式)
  3. 系统维护For流星无语
  4. hashmap为什么用红黑树_要看HashMap源码,先来看看它的设计思想
  5. 汉子编码比字母编码长_字母/博客作者编码问题(使用动态编程)
  6. Python+OpenCV:姿态估计(Pose Estimation)
  7. 在ubuntu - linux系统下装TensorFlow(虚拟机)
  8. 从IBM的计划中分析出中国重新相当然的错误选择吗
  9. 使用框架建立富联网应用
  10. Stata: 空间计量模型溢出效应的动态呈现
  11. JS中编码的三种方法
  12. python3一键排版证件照(一寸照、二寸照),附源代码
  13. 快速排序-C语言版(带图详细)
  14. 我被开除了。。只因为看了骂公司的帖子
  15. 常见的总线通信方式及其特点
  16. Json汉化-使用JavaScript和百度翻译API免费实现Json文件的汉化
  17. Connect Four四子棋c++程序 - 显示窗口(0)
  18. 在HTML页面显示时钟
  19. 交社保竟然还能领失业补助金,自己尝试去申请
  20. 自然语言处理训练营NLP--笔记

热门文章

  1. C语言必考100题,C语言必考100题.doc
  2. 物联网+Android+甲烷控制系统
  3. cancase lin管脚_Atmel针对汽车市场推出CAN与LIN收发器系列
  4. 杂项-数学软件:Mathematica
  5. 线性判别分析法(LDA)
  6. 复旦研究生创办食品安全网站 称国人易粪相食
  7. 如何使用OpenCV+Python去除手机拍摄文本底色
  8. 上网不要老是校内和QQ,这些没有登过你就白读大学了!
  9. 不要在二三十岁时就开始老去
  10. java pptx转图_Java如何将PPT的幻灯片转换为图片?