ViewModel使用场景
- 当横竖屏切换时,希望数据不丢失,可以用ViewModel当成存储媒介;
- 可作为Activity & Fragment通讯的媒介;
ViewModel的创建
//Activity中构建MyViewModel
ViewModelProvider(this).get(MyViewModel::class.java)
//ViewModelProviders类中
public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
: NewInstanceFactory.getInstance());//1
}
//ViewModelStore类中
public class ViewModelStore {
private final HashMap<String, ViewModel> mMap = new HashMap<>();//2
- 注释1:构建ViewModelProvider的参数有两个,第一个参数owner.getViewModelStore(),它是vm的存储器,会对vm进行缓存;第二个参数是构建vm的Factory,默认是SavedStateViewModelFactory类型,其内部通过反射构建ViewModel,比较简单就不展开了;
- 注释2:ViewModelStore用HashMap缓存vm,说到缓存,好像都喜欢用hashmap;
得到ViewModelProvider实例后,通过get获取ViewModel;
//ViewModelProvider类中
public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {
......
return get(DEFAULT_KEY + ":" + canonicalName, modelClass);//调用下面两个参数的重载函数,传入类名作为key,保证Activity同类型vm只有一个实例
}
//ViewModelProvider类中
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
ViewModel viewModel = mViewModelStore.get(key);//1
if (modelClass.isInstance(viewModel)) {
......
return (T) viewModel;
} else {
......
}
......
viewModel = mFactory.create(modelClass);//2
mViewModelStore.put(key, viewModel);//3
return (T) viewModel;
}
- 注释1:通过ViewModel存储器来查找,如果有缓存则返回对象;
- 注释2:工厂构建ViewModel,工厂实现具体可以看SavedStateViewModelFactory;
- 注释3:缓存vm,与注释1对应;
横竖屏切换,ViewModel如何能做到数据不丢失呢?
只要保证横竖屏切换前后,Activity获取到的ViewModelStore(owner.getViewModelStore())是同一个实例应该就可以了吧。
看下owner.getViewModelStore()巧妙的地方
getViewModelStore()的实现在Activity的父类ComponentActivity中
//ComponentActivity类中
public ViewModelStore getViewModelStore() {
......
ensureViewModelStore();//1
return mViewModelStore;
}
void ensureViewModelStore() {
if (mViewModelStore == null) {
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {//1
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {//2
mViewModelStore = new ViewModelStore();
}
}
}
- 注释1:getLastNonConfigurationInstance()不为空,则给mViewModelStore赋值,看注释得知NonConfigurationInstances缓存了viewModelStore;
- 注释2:如果mViewModelStore为空则构建;
- 到这里我们得知,getLastNonConfigurationInstance是获取缓存viewModelStore入口,对应横竖屏切换后获取vm的场景,那么是否就提供了保存viewModelStore的入口,对应横竖屏切换前保存vm的场景;
//ComponentActivity类中
public final Object onRetainNonConfigurationInstance() {
......
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
- 代码比较简单,构建NonConfigurationInstances,将viewModelStore赋值给内部属性;
onRetainNonConfigurationInstance提供了保存viewModelStore的入口,那么它是在哪里被调用呢,应该不是Activity,因为横竖屏切换Activity对象显然就被销毁了,那么就有必要了解下横竖屏切换的流程。
横竖屏切换的大体流程
ActivityThread.handleRelaunchActivity是横竖屏切换的入口,当时分析销毁恢复的时候有一个误区,以为就是AMS先handleDestroyActivity再handleLaunchActivity,没想到还有一个handleRelaunchActivity函数。
//ActivityThread类中
public void handleRelaunchActivity(ActivityClientRecord tmp,
PendingTransactionActions pendingActions) {
......
handleRelaunchActivityInner(r, configChanges, tmp.pendingResults, tmp.pendingIntents,
pendingActions, tmp.startsNotResumed, tmp.overrideConfig, "handleRelaunchActivity");//主要调用handleRelaunchActivityInner
......
}
//ActivityThread类中
private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
PendingTransactionActions pendingActions, boolean startsNotResumed,
Configuration overrideConfig, String reason) {
......
handleDestroyActivity(r.token, false, configChanges, true, reason);//销毁
......
handleLaunchActivity(r, pendingActions, customIntent);//重建
}
- 这里的核心是销毁跟重建Activity,猜测handleDestroyActivity对ViewModelStore进行保存,handleLaunchActivity把保存的ViewModelStore再丢给Activity。
看下ActivityThread.handleDestroyActivity销毁的过程
public void handleDestroyActivity(IBinder token, boolean finishing, int configChanges,
boolean getNonConfigInstance, String reason) {
ActivityClientRecord r = performDestroyActivity(token, finishing,
configChanges, getNonConfigInstance, reason);//调用下面5个参数重载的函数
......
}
ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
int configChanges, boolean getNonConfigInstance, String reason) {
ActivityClientRecord r = mActivities.get(token);//1
.....
r.lastNonConfigurationInstances
= r.activity.retainNonConfigurationInstances();//2
.....
return r;
}
- 注释1:根据token获取ActivityClientRecord,这里很关键,跟恢复Activity用是同一个对象;
- 注释2:这里代码是不是有点熟悉,但还不是最终的代码,跟进去看看;
NonConfigurationInstances retainNonConfigurationInstances() {
Object activity = onRetainNonConfigurationInstance();//1;
......
NonConfigurationInstances nci = new NonConfigurationInstances();//2
nci.activity = activity;
nci.children = children;
nci.fragments = fragments;
nci.loaders = loaders;
......
return nci;
}
- 注释1:这里可能有会点绕,得仔细看下,onRetainNonConfigurationInstance函数被ComponentActivity重写了,这里返回的对象类型是ComponentActivity.NonConfigurationInstances,它维护ViewModelStore属性;
- 注释2:这里的类型是Activity.NonConfigurationInstances,它的activity属性是ComponentActivity.NonConfigurationInstances类型;
- 所以最终被保存的Activity.NonConfigurationInstances类型对象;
- 持有关系:Activity.NonConfigurationInstances 持有 ComponentActivity.NonConfigurationInstances对象,后者持有ViewModelStore对象;
类图如下,可以对照源码看下
销毁流程小结
ActivityThread会间接将ViewModelStore保存到ActivityClientRecord当中,以便恢复时使用,注意这里是间接,因为这中间涉及多个数据对象;
看下ActivityThread.handleLaunchActivity恢复的过程
//ActivityThread类中
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
......
final Activity a = performLaunchActivity(r, customIntent);//调用下面3个参数的重载函数
......
return a;
}
//ActivityThread类中
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback);//1
.....
return activity;
}
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken,
IBinder shareableActivityToken) {
......
mLastNonConfigurationInstances = lastNonConfigurationInstances;//2
......
}
- 注释1:调用attch函数,注意看这个参数r.lastNonConfigurationInstances;
- 注释2:看到这里是不是就很熟悉了,将横竖屏前保存的lastNonConfigurationInstances取出赋值,注意它里面间接维护了ViewModelStore;
恢复流程小结
ActivityThread间接将ViewModelStore通过attach函数再丢给Activity,注意这里是间接,因为这中间涉及多个数据对象;
流程图
注意是间接
ViewModel.onCleared何时会被调用
- Activity销毁(非横竖屏切换)
//ComponentActivity类中
public ComponentActivity() {
Lifecycle lifecycle = getLifecycle();
......
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
if (!isChangingConfigurations()) {
getViewModelStore().clear();
}
}
}
});
......
}
构造函数注册监听,当不是因为横竖屏导致的销毁,就会清空ViewModelStore,也就是清空ViewModel;
- 同类型的vm被get两次,那么第一个vm对象会被清理。
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();//旧vm被清理
}
}
ViewModel & AndroidViewModel区别
后者带Application对象,前者没有。 前面分析的得知,构建vm的工厂是SavedStateViewModelFactory
//ViewModelProvider类中
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
......
viewModel = mFactory.create(modelClass);//工厂构建vm,工厂是SavedStateViewModelFactory类型
return (T) viewModel;
}
//SavedStateViewModelFactory类中
public <T extends ViewModel> T create(@NonNull String key, @NonNull Class<T> modelClass) {
......
try {
T viewmodel;
if (isAndroidViewModel && mApplication != null) {
viewmodel = constructor.newInstance(mApplication, controller.getHandle());
} else {
viewmodel = constructor.newInstance(controller.getHandle());
}
return viewmodel;
}
......
}
- 如果是vm是AndroidViewModel类型,反射构建vm的时候传入mApplication对象;SavedStateViewModelFactory是在ComponentActivity中构建,构建的时候会对其mApplication对象赋值;
ViewModel & onSaveInstanceState 场景区别
- 相同的
都可以保存数据;
- 不同点
- 通过onSaveInstanceState保存的数据,最终会到达Binder缓冲区,缓冲区只有1M的空间,所以只能存储轻量级的数据,并且涉及到跨进程通信会额外的开销(序列化、反序列化);
- ViewModel的数据是保存在内存中,不会有额外开销;
、
MVVM 中的VM思考
我们通常会把MVVM的VM跟ViewModel等同,其实我觉得不一定。ViewModel可以当成VM层来使用,但其他满足View跟Model之间数据驱动的、做业务处理的层,都可以是VM层,例如把Presenter改成用LiveData做数据驱动,也可以算是VM。
涉及类
- ViewModel、AndroidViewModel,均提供数据存储,后者持有Application对象;
- ViewModeStore,vm仓库,负责vm的缓存以及触发清理;
- SavedStateViewModelFactory,构建vm的工厂类;
- ViewModelProvider,vm提供者,负责维护ViewModeStore以及ViewModelProvider.Factory;
- ActivityClientRecord,横竖屏转换时维护ViewModeStore对象;
总结
- vm之所以在横竖屏切换后保证数据不丢失,是因为vm的仓库ViewModelStore会被ActivityClientRecord保存,用于恢复后重新赋值,所以也就保证了vm数据不会丢失;
- Activity销毁(非横竖屏切换)以及同类型的vm被get两次,会触发vm onClear函数。
以上分析有不对的地方,请指出,互相学习,谢谢哦!
网友评论