ViewModel注重以生命周期的方法存储和管理界面相关的数据,ViewModel类可在屏幕发生旋转等配置更改后仍然保存。在没有ViewModel之前我们保存应用是通过onSaveInstanceState()和onCreate()方法来完成的,但是此方法不适合大量数据的保存和恢复。另外一个问题是,有些数据是异步获取的,还夹杂着业务逻辑,这样可能会使View层逻辑比较复杂,比较容易引发各种问题,而ViewModel的引入,向开发者隐藏了数据的保存和恢复逻辑,节省了模板代码的编写,提高了开发效率。所以接下来我们来看下如果使用ViewModel吧
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<List<User>>();
loadUsers();
}
return users;
}
private void loadUsers() {
// Do an asynchronous operation to fetch users.
}
}
public class MyActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
// Create a ViewModel the first time the system calls an activity's onCreate() method.
// Re-created activities receive the same MyViewModel instance created by the first activity.
MyViewModel model = new ViewModelProvider(this).get(MyViewModel.class);
model.getUsers().observe(this, users -> {
// update UI
});
}
}
以上代码来自AndroidDeveloper官网。那么ViewModel是怎么实现在Activity销毁后重建的呢?首先我们来看ViewModel是如何获取到的
ViewModelProvider viewModelProvider = new ViewModelProvider(this);
userViewModel = viewModelProvider.get(UserViewModel.class);
以上两行代码为我们解答了疑问,首先ViewModelProvider 是Activity持有的一个成员变量,而UserViewModel则是ViewModelProvider中保存的某个缓存。接着我们打开ViewModelProvider源码,
public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
: NewInstanceFactory.getInstance());
}
我们发现Activity被当成了ViewModelStoreOwner传递进来,第二行代码通过viewModelProvider.get(UserViewModel.class)获取到了ViewModel对象方法,点开get方法源码
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);
}
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> 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;
}
通过以上代码我们发现ViewModel在这里被创建,并且被存在了ViewModelStore里面了。鉴于我们现在是在研究ViewMode在设备配置发生改变时是如果被保存和恢复的,所以我们就不分析ViewModel的创建过程了,我们只需要知道它被创建后保存在了ViewModelStore中就行了,那么ViewMdoelStore是哪里来的呢?就是通过ComponentActivity的LifecylceOwner接口返回的,所以我们的ViewModel数据还是保存在Activity中的。那么ViewModelStore是哪里来的?请看以下代码
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;
}
通过以上代码我们发现ViewModel优先取自NonConfigurationInstances,如果没有,就需要重新new一个,所以我们猜测,如果Activity是全新构建的这个时候NonConfigurationInstances中的ViewModel是空的,因为旋转重建后就不会是空的。所以我们弄清楚NonConfigurationInstances的来源就可以知道ViewModel是如何恢复的了。查看Activity的源码我们发现NonConfigurationInstances是attch方法传递进来的,所以我测试和Activity启动有关。所以我去ActivityThread中搜索了activity.attach字符串还真的有,就在android.app.ActivityThread#performLaunchActivity中,这个方法的调用源头在android.app.ActivityThread#handleRelaunchActivity方法中,从名字就可以看出这个方法是处理Activity的重启的。而NonConfigurationInstances就保存在该方法的入参ActivityClientRecord中;我们看下ActivityClientRecord类,他是记录Activity的一个辅助类.
public static final class ActivityClientRecord {
public IBinder token;
int ident;
Intent intent;
String referrer;
IVoiceInteractor voiceInteractor;
Bundle state;
PersistableBundle persistentState;
Activity activity;
Window window;
Activity parent;
String embeddedID;
Activity.NonConfigurationInstances lastNonConfigurationInstances;
}
所以我们的ViewModel在Activity的重建过程中被传进来了。就实现了ViewModel的恢复;但是ViewModel是什么时候被存在NonConfigurationInstances中的呢?答案在android.app.ActivityThread#handleRelaunchActivityInner里,这个方法在Activity需要销毁重建时调用。
handleDestroyActivity(r.token, false, configChanges, true, reason);
performDestroyActivity(token, finishing,configChanges, getNonConfigInstance, reason)
activity.retainNonConfigurationInstances()
通过以上方法轨迹我们最后发现activity.retainNonConfigurationInstances()返回了NonConfigurationInstances对象并且赋值给了ActivityClientRecord 。所以谜题解开了。是ActivityThread和AMS通过ActivityClientRecord完成了ViewModel的恢复和保存。最后我们看下activity.retainNonConfigurationInstances方法
NonConfigurationInstances retainNonConfigurationInstances() {
Object activity = onRetainNonConfigurationInstance();
HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
// We're already stopped but we've been asked to retain.
// Our fragments are taken care of but we need to mark the loaders for retention.
// In order to do this correctly we need to restart the loaders first before
// handing them off to the next activity.
mFragments.doLoaderStart();
mFragments.doLoaderStop(true);
ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
if (activity == null && children == null && fragments == null && loaders == null
&& mVoiceInteractor == null) {
return null;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.activity = activity;
nci.children = children;
nci.fragments = fragments;
nci.loaders = loaders;
if (mVoiceInteractor != null) {
mVoiceInteractor.retainInstance();
nci.voiceInteractor = mVoiceInteractor;
}
return nci;
}
在代码段后面我们发现返回了NonConfigurationInstances对象实例,其中的nci.activity对象保存了onRetainNonConfigurationInstance()方法返回的对象,这个方法返回的对象就保存了ViewModel.
网友评论