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
@Override
public 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 方法做了什么
@MainThread
public <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 方法
@MainThread
public <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 StatementWithEmptyBody
if (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 {
// 果不其然,内部有一个 HashMap
private final HashMap<String, ViewModel> mMap = new HashMap<>();
final v
oid 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()
@Override
public 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 NonConfigurationInstances
mViewModelStore = 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()}
*/
@Nullable
public 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 NonConfigurationInstance
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
viewModelStore = nc.viewModelStore;
}
}
// 依然为空,说明没有需要缓存的,则返回 null
if (viewModelStore == null && custom == null) {
return null;
}
// 创建 NonConfigurationInstances 对象,并赋值 viewModelStore
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
到这儿我们大概明白了,Activity 在因配置更改而销毁重建过程中会先调用 onRetainNonConfigurationInstance 保存 viewModelStore 实例。
在重建后可以通过 getLastNonConfigurationInstance 方法获取之前的 viewModelStore 实例。
现在解决了第一个问题:为什么Activity旋转屏幕后ViewModel可以恢复数据
再看第三个问题:什么时候 ViewModel#onCleared() 会被调用
最后
答应大伙的备战金三银四,大厂面试真题来啦!
这份资料我从春招开始,就会将各博客、论坛。网站上等优质的Android开发中高级面试题收集起来,然后全网寻找最优的解答方案。每一道面试题都是百分百的大厂面经真题+最优解答。包知识脉络 + 诸多细节。
节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。
《960全网最全Android开发笔记》
《379页Android开发面试宝典》
包含了腾讯、百度、小米、阿里、乐视、美团、58、猎豹、360、新浪、搜狐等一线互联网公司面试被问到的题目。熟悉本文中列出的知识点会大大增加通过前两轮技术面试的几率。
如何使用它?
1.可以通过目录索引直接翻看需要的知识点,查漏补缺。
2.五角星数表示面试问到的频率,代表重要推荐指数
《507页Android开发相关源码解析》
只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。
真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。
腾讯、字节跳动、阿里、百度等BAT大厂 2020-2021面试真题解析
资料收集不易,如果大家喜欢这篇文章,或者对你有帮助不妨多多点赞转发关注哦。文章会持续更新的。绝对干货!!!