为什么要使用ViewModel?
在日常开发中,横竖屏切换是非常常见的功能,由于横竖屏切换会使得
Activity
重建,导致界面相关数据都会丢失。为了避免这种情况,一般会有两种做法:第一种是在AndroidManifest.xml
文件中,将Activity
的一个属性设置为android:configChanges="orientation|keyboardHidden|screenSize"
;第二种方案是使用onSaveInstanceState
方法保存数据,但此方法仅适合可以序列化和反序列化的少量数据,而不适合数量可能较大的数据,如用户列表或位图。在使用MVP架构时,当View层使用Presenter层去异步加载一个耗时任务,若在任务结果返回回来之前,界面已经被销毁,我们都需要手动判断View层的状态;若Presenter层还有持有了View层的
Context
,若不清理掉的话可能会造成内存泄露。
ViewModel的出现能够很优雅地解决上述两个问题。
简单用法
// 1. 创建一个继承ViewModel的类
public class MyVideoModel extends ViewModel {}
// 2. 创建一个ViewModelProvider实例
ViewModelProvider provider = new ViewModelProvider(this);
// 3. 通过provider获取MyVideoModel实例
MyVideoModel videoModel = provider.get(MyVideoModel.class);
源码分析
先来看看第2步创建ViewModelProvider
时做了些什么事
public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
: NewInstanceFactory.getInstance());
}
第一个参数调用了owner.getViewModelStore()
,这个ViewModelStoreOwner
是一个接口,我们继承的父类Activity
--ComponentActivity
实现了这个接口。
@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.");
}
if (mViewModelStore == null) {
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
当我们在自己的Activity#onCreate
方法内new ViewModelProvider(this);
时,这个
mViewModelStore
就已经不为空了,所以直接返回。ViewModelStore
就是用来保存我们自己创建的
ViewModel
对象。那么它是什么时候被创建赋值的呢?在FragmentActivity#onCreate
方法内调用了
mFragments.attachHost(null /*parent*/);
// FragmentActivity.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
mFragments.attachHost(null /*parent*/);
...
super.onCreate(savedInstanceState);
...
}
// FragmentController.java
public void attachHost(@Nullable Fragment parent) {
mHost.mFragmentManager.attachController(
mHost, mHost /*container*/, parent);
}
// FragmentManagerImpl.java
public void attachController(@NonNull FragmentHostCallback host,
@NonNull FragmentContainer container, @Nullable final Fragment parent) {
...
// Get the FragmentManagerViewModel
if (parent != null) {
mNonConfig = parent.mFragmentManager.getChildNonConfig(parent);
} else if (host instanceof ViewModelStoreOwner) {
ViewModelStore viewModelStore = ((ViewModelStoreOwner) host).getViewModelStore();
mNonConfig = FragmentManagerViewModel.getInstance(viewModelStore);
} else {
mNonConfig = new FragmentManagerViewModel(false);
}
}
attachController
方法中的parent
为空,所以不会走第一个if
条件;第一个参数host
,它的实现类是
HostCallbacks
。
class HostCallbacks extends FragmentHostCallback implements
ViewModelStoreOwner,
OnBackPressedDispatcherOwner {
...
@NonNull
@Override
public ViewModelStore getViewModelStore() {
return FragmentActivity.this.getViewModelStore();
}
...
}
再回到ComponentActivity#getViewModelStore方法
@NonNull
@Override
public ViewModelStore getViewModelStore() {
...
if (mViewModelStore == null) {
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
// Activity第一次启动时,得到nc为null。但是在横竖屏切换时,这个nc不为空了
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
// 所以这里就拿到了之前保存的ViewModelStore,也就意味着拿到之前我们的ViewModel实例。
// 后面会继续分析到
mViewModelStore = nc.viewModelStore;
}
// 执行这里
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
此时再回到上面创建ViewModelProvider
时的第二个参数,因为ComponentActivity
并没有实现
HasDefaultViewModelProviderFactory
,所以第二个参数的类型是NewInstanceFactory
。第2步源码分析完成。
接下来看第3步源码实现。
@NonNull
@MainThread
public T get(@NonNull Class 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);
}
继续追踪get的重载函数
@NonNull
@MainThread
public T get(@NonNull String key, @NonNull Class modelClass) {
// 注释1
ViewModel viewModel = mViewModelStore.get(key);
if (modelClass.isInstance(viewModel)) {
if (mFactory instanceof OnRequeryFactory) {
((OnRequeryFactory) mFactory).onRequery(viewModel);
}
return (T) viewModel;
} else {
//noinspection StatementWithEmptyBody
if (viewModel != null) {
// TODO: log a warning.
}
}
// 注释2
if (mFactory instanceof KeyedFactory) {
viewModel = ((KeyedFactory) mFactory).create(key, modelClass);
} else {
// 注释3
viewModel = mFactory.create(modelClass);
}
mViewModelStore.put(key, viewModel);
return (T) viewModel;
}
方法中的key为androidx.lifecycle.ViewModelProvider.DefaultKey:xxx.xxx.MyViewModel
,
modelClass
就是我们自己传的MyViewModel.class
。注释1处代码第一次执行时肯定为空,从第2步源码分析可知mFactory
的类型为NewInstanceFactory
,所以会执行到第注释3。通过反射获取到我们自己的
ViewModel
对象,然后将其保存到ViewModelStore
中。
当因配置更新导致界面重建时如何做到保存数据的?
当界面发生横竖屏切换时,Activity
会被销毁再重建,在调用onDestroy
方法之前系统会调用一个方法
// Activity.java
/**
* Called by the system, as part of destroying an
* activity due to a configuration change, when it is known that a new
* instance will immediately be created for the new configuration. You
* can return any object you like here, including the activity instance
* itself, which can later be retrieved by calling
* {@link #getLastNonConfigurationInstance()} in the new activity
* instance.
*/
public Object onRetainNonConfigurationInstance() {
return null;
}
来看看ComponentActivity中是如何将其重写的
@Override
@Nullable
public final Object onRetainNonConfigurationInstance() {
// 这里直接返回的是null
Object custom = onRetainCustomNonConfigurationInstance();
ViewModelStore viewModelStore = mViewModelStore;
// 正常情况下,此时的mViewModelStore不可能为空
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;
}
}
if (viewModelStore == null && custom == null) {
return null;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
根据代码中的注释,最终ViewModelStore
对象被保存在ComponentActivity
的内部类
NonConfigurationInstances
对象中。这个方法是在Activity
中被调用的。
// Activity.java
NonConfigurationInstances retainNonConfigurationInstances() {
Object activity = onRetainNonConfigurationInstance();
...
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.activity = activity;
...
return nci;
}
将ComponentActivity#NonConfigurationInstances
对象赋值给了
Activity#NonConfigurationInstances
对象的activity
属性。而retainNonConfigurationInstances
方法是在Activity执行onDestroy
生命周期方法之前执行的。
// ActivityThread.java
/** Core implementation of activity destroy call. */
ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
int configChanges, boolean getNonConfigInstance, String reason) {
ActivityClientRecord r = mActivities.get(token);
...
if (getNonConfigInstance) {
try {
// 将其返回给了ActivityClientRecord属性
r.lastNonConfigurationInstances
= r.activity.retainNonConfigurationInstances();
} catch (Exception e) {
...
}
}
try {
r.activity.mCalled = false;
// 执行onDestroy方法
mInstrumentation.callActivityOnDestroy(r.activity);
...
} catch (Exception e) {
...
}
return r;
}
最终mViewModelStore
对象被保存在ActivityClientRecord
对象的
lastNonConfigurationInstances
属性上。很显然,mActivities
属性的生命周期与ActivityThread
保持一致,那么lastNonConfigurationInstances
也一样,因此不会受Activity
的销毁再重建的影响。
当Activity
重建时,又会执行onCreate
方法,此时,我们再回到getViewModelStore
方法
@NonNull
@Override
public ViewModelStore getViewModelStore() {
...
if (mViewModelStore == null) {
// 会执行到这里
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
@Nullable
public Object getLastNonConfigurationInstance() {
return mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.activity : null;
}
mLastNonConfigurationInstances
不为空,所以直接返回它的属性activity
的值。还记得这个属性保存的是什么值吗?上文已经提到过了,它就是ComponentActivity
的NonConfigurationInstances
对象,而它的viewModelStore
就保存着横竖屏销毁前的那个ViewModelStore
对象,那也就意味着拿到了之前的ViewModel
对象。
那mLastNonConfigurationInstances
这个属性是在哪里被赋值的呢?它是Activity
对象在ActivityThread
中被创建后,调用其attach
方法时进行赋值的。上文也提到过,我们的ViewModel
被保存在ViewModelStore
,而ViewModelStore
又被保存在CompponentActivity#NonConfigurationInstances
对象的viewModelStore
属性上,而这个对象又被保存到了Activity#NonConfigurationInstances
对象的activity
属性上,它又被保存到了ActivityThread#ActivityClientRecord
对象的lastNonConfigurationInstances
属性上。