@NonNull@OverridepublicViewModelStoregetViewModelStore(){if(getApplication()==null){thrownewIllegalStateException("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 =newViewModelStore();}}return mViewModelStore;}
@NonNull
ViewModelStore getViewModelStore(@NonNull Fragment f) {
return mNonConfig.getViewModelStore(f);
}
mNonConfig是一个ViewModel,FragmentManagerViewModel
privateFragmentManagerViewModel mNonConfig;/**
* FragmentManagerViewModel is the always up to date view of the Fragment's
* non configuration state
* 这是一个专门用于用于管理Fragment的一些 状态 的 ViewModel
*/finalclassFragmentManagerViewModelextendsViewModel{
一、跟踪ViewModel的创建以及保存过程。ViewModelProvider(this).get(MainViewModel::class.java)ViewModel是通过ViewModelProvider创建的,ViewModelProvider里面只有两个成员。 private final Factory mFactory; private final ViewModelStore mViewModelStore;这两个成员分别负责创建ViewModel和保存ViewMo