ComponentActivity持有一个ViewModelStore,可以通过ViewModelStoreOwner中的getViewModelStore()方法获取。(为啥不直接在Activity获取ViewModelStore,再获取ViewModel呢?因为ViewModel要通过ViewModelProvider.Factory创建)
Factory:是一个接口,用来创建ViewModel的
3.2 ViewModelProvider #get()
@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”);
}
//构造了一个key
return get(DEFAULT_KEY + “:” + canonicalName, modelClass);
}
@MainThread
public T get(@NonNull String key, @NonNull Class modelClass) {
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.
}
}
if (mFactory instanceof KeyedFactory) {
viewModel = ((KeyedFactory) (mFactory)).create(key, modelClass);
} else {
viewModel = (mFactory).create(modelClass);
}
mViewModelStore.put(key, viewModel);
return (T) viewModel;
}
调用get方法后,会调用第二个get方法,传递key(DEFAULT_KEY + “:” + canonicalName)给第二个get方法
首先根据提供的key从ViewModelStore中获取一个ViewModel对象
如果这个获取到的ViewModel对象实例存在,那么就将其返回
如果该ViewModel对象不存在,就通过Factory创建一个ViewModel对象,并将其存储到ViewModelStore中,并将这个新创建的ViewModel对象返回。
这里面存在三个Factory:Factory,KeyedFactory和OnrequeryFactory,keyedFactory和Factory相比就是create方法中多了一个key参数。
ViewModelStore获取到ViewModel时,会判断当前mFactory是否是OnRequeryFactory类型的,是的话会回调onRequery方法
那么OnRequeryFactory回调onRequery有什么用呢?其实ViewModel不仅可以因为配置改变可以恢复Activity数据,也能恢复因为系统资源紧张而回收掉的Activity数据,只不过后者需要依靠SaveStateHandler
总结:ViewModelProvider获取到ViewModel:
1,首先创建ViewModelProvider传入ViewModelStoreOwner和Factory 2,调用ViewModelProvider的get方法,从ViewModelStore中获取ViewModel,有则直接返回,没有就创建后返回。
4. ViewModel的恢复
ViewModel是从ViewModelStore中获取
ViewModelStore是通过ViewModelStoreOwner.getViewModelStore方法获取
ComponentActivity实现了ViewModelStoreOwner接口和HasDefaultViewModelProviderFactory
4.1 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;
}
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();
}
}
}
getViewModelStore()通过两种方法获取到ViewModelStore
1,从NonConfigurationInstances中拿到
2,new一个出来
NonConfigurationInstances,用来包装不受配置更改影响的数据
Activity的NonConfigurationInstances在系统配置改变时保存了ViewModelStore和fragments等
4.2 ActivityThread #handleRelaunchActivity
系统配置发生改变时,AMS会调用ActivityThread的handleRelaunchActivity,并且通过当前Activity对应的ActivityRecord构建一个ActivityClientRecord传递过来
Activity的生命周期方法是在ActivityThread中执行的
private void handleRelaunchActivity(ActivityClientRecord tmp) {
…
//注意最后一个参数getNonConfigInstance为true,如果是正常退出Activity的走到onDestory的该参数为false
handleDestroyActivity(r.token, false, configChanges, true);
…
handleLaunchActivity(r, currentIntent, “handleRelaunchActivity”);
}
private void handleDestroyActivity(IBinder token, boolean finishing,
int configChanges, boolean getNonConfigInstance) {
ActivityClientRecord r = performDestroyActivity(token, finishing,
configChanges, getNonConfigInstance);
}
4.2 ActivityThread #performDestroyActivity
ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
int configChanges, boolean getNonConfigInstance, String reason) {
…
//注意此时ActivityClientRecord并未从mActivities中移除,只有执行完Destroy才会移除
ActivityClientRecord r = mActivities.get(token);
performPauseActivityIfNeeded(r, “destroy”);
if (!r.stopped) {
//执行Activity的onStop()方法
callActivityOnStop(r, false /* saveState */, “destroy”);
}
/此时为true,正常退出的为false
if (getNonConfigInstance) {
try {
//调用对应Activity的retainNonConfigurationInstances方法
//返回值NonConfigurationInstance赋给ActivityClientRecord内的lastNonConfigurationInstances持有
r.lastNonConfigurationInstances
= r.activity.retainNonConfigurationInstances();
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
…
}
}
}
/最终回调到onDestroy方法
mInstrumentation.callActivityOnDestroy(r.activity);
…
}
Activity的retainNonConfigurationInstances 调用了onRetainNonConfigurationInstance
4.3 ComponentActivity # onRetainNonConfigurationInstance()
public final Object onRetainNonConfigurationInstance() {
// Maintain backward compatibility.
Object custom = onRetainCustomNonConfigurationInstance();
ViewModelStore viewModelStore = mViewModelStore;
if (viewModelStore == null) {
// No one called getViewModelStore(),从lastNonConfigurationInstance取出viewModelStore
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
viewModelStore = nc.viewModelStore;
}
}
if (viewModelStore == null && custom == null) {
return null;
}
//创建一个NonConfigurationInstances,将此时的mViewModelStore设置进去
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
在调用onDestory()方法前,会创建一个NonConfigurationInstances对象,将viewModelStore存储在NonConfigurationInstances,然后将NonConfigurationInstances存储在ActivityClientrecord中。
4.4 ActivityThread #performLaunchActivity
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,
r.assistToken);
}
…
ActivityThread的handleLaunchActivity最终会调用 performLaunchActivity,最终调用到activity.attach,传入了lastNonConfigurationInstances
这样对于新的Activity来说,获取到的就是之前Activity的NonConfigurationInstance,其中的ViewModelStore也是之前的,ViewModel自然也是之前的。
这样就保证了在系统配置改变时,ViewModel不变了。
总结:
文末
面试:如果不准备充分的面试,完全是浪费时间,更是对自己的不负责!
不管怎么样,不论是什么样的大小面试,要想不被面试官虐的不要不要的,只有刷爆面试题题做好全面的准备,当然除了这个还需要在平时把自己的基础打扎实,这样不论面试官怎么样一个知识点里往死里凿,你也能应付如流啊
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门,即可获取!