//activity/activity/src/main/java/androidx/activity/ComponentActivity.java@NonNull@OverridepublicViewModelProvider.FactorygetDefaultViewModelProviderFactory(){if(getApplication()==null){thrownewIllegalStateException("Your activity is not yet attached to the "+"Application instance. You can't request ViewModel before onCreate call.");}if(mDefaultFactory==null){mDefaultFactory=newSavedStateViewModelFactory(getApplication(),this,getIntent()!=null?getIntent().getExtras():null);}returnmDefaultFactory;}
//lifecycle/lifecycle-viewmodel/src/main/java/androidx/lifecycle/ViewModelProvider.ktpublicopenoperatorfun<T:ViewModel>get(modelClass:Class<T>):T{valcanonicalName=modelClass.canonicalName?:throwIllegalArgumentException("Local and anonymous classes can not be ViewModels")returnget("$DEFAULT_KEY:$canonicalName",modelClass)}
//lifecycle/lifecycle-viewmodel/src/main/java/androidx/lifecycle/ViewModelProvider.ktpublicopenoperatorfun<T:ViewModel>get(key:String,modelClass:Class<T>):T{//调用ViewModelStore的重载运算符判断是否有缓存valviewModel=store[key]if(modelClass.isInstance(viewModel)){(factoryas?OnRequeryFactory)?.onRequery(viewModel)returnviewModelasT}else{@Suppress("ControlFlowWithEmptyBody")if(viewModel!=null){// TODO: log a warning.}}valextras=MutableCreationExtras()extras[VIEW_MODEL_KEY]=keyreturnfactory.create(modelClass,CombinedCreationExtras(extras,defaultCreationExtras)).also{store.put(key,it)}}
//lifecycle/lifecycle-viewmodel-savedstate/src/main/java/androidx/lifecycle/SavedStateViewModelFactory.javapublic<TextendsViewModel>Tcreate(@NonNullStringkey,@NonNullClass<T>modelClass){// empty constructor was called.if(mLifecycle==null){thrownewUnsupportedOperationException("SavedStateViewModelFactory constructed "+"with empty constructor supports only calls to "+"create(modelClass: Class<T>, extras: CreationExtras).");}booleanisAndroidViewModel=AndroidViewModel.class.isAssignableFrom(modelClass);Constructor<T>constructor;if(isAndroidViewModel&&mApplication!=null){constructor=findMatchingConstructor(modelClass,ANDROID_VIEWMODEL_SIGNATURE);}else{constructor=findMatchingConstructor(modelClass,VIEWMODEL_SIGNATURE);}// doesn't need SavedStateHandleif(constructor==null){returnmFactory.create(modelClass);}SavedStateHandleControllercontroller=LegacySavedStateHandleController.create(mSavedStateRegistry,mLifecycle,key,mDefaultArgs);Tviewmodel;if(isAndroidViewModel&&mApplication!=null){viewmodel=newInstance(modelClass,constructor,mApplication,controller.getHandle());}else{viewmodel=newInstance(modelClass,constructor,controller.getHandle());}viewmodel.setTagIfAbsent(TAG_SAVED_STATE_HANDLE_CONTROLLER,controller);returnviewmodel;}
privatestatic<TextendsViewModel>TnewInstance(@NonNullClass<T>modelClass,Constructor<T>constructor,Object...params){try{returnconstructor.newInstance(params);}catch(IllegalAccessExceptione){thrownewRuntimeException("Failed to access "+modelClass,e);}catch(InstantiationExceptione){thrownewRuntimeException("A "+modelClass+" cannot be instantiated.",e);}catch(InvocationTargetExceptione){thrownewRuntimeException("An exception happened in constructor of "+modelClass,e.getCause());}}
@Override@NullablepublicfinalObjectonRetainNonConfigurationInstance(){//旋转屏幕会触发该方法调用 将ViewModelStore存储到NonConfigurationInstances中Objectcustom=onRetainCustomNonConfigurationInstance();ViewModelStoreviewModelStore=mViewModelStore;if(viewModelStore==null){// No one called getViewModelStore(), so see if there was an existing// ViewModelStore from our last NonConfigurationInstanceNonConfigurationInstancesnc=(NonConfigurationInstances)getLastNonConfigurationInstance();if(nc!=null){viewModelStore=nc.viewModelStore;}}if(viewModelStore==null&&custom==null){returnnull;}NonConfigurationInstancesnci=newNonConfigurationInstances();nci.custom=custom;nci.viewModelStore=viewModelStore;returnnci;}
@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){//调用getLastNonConfigurationInstance方法获取NonConfigurationInstances对象NonConfigurationInstancesnc=(NonConfigurationInstances)getLastNonConfigurationInstance();if(nc!=null){// Restore the ViewModelStore from NonConfigurationInstancesmViewModelStore=nc.viewModelStore;}if(mViewModelStore==null){mViewModelStore=newViewModelStore();}}returnmViewModelStore;}
publicclassViewModelStore{privatefinalHashMap<String,ViewModel>mMap=newHashMap<>();finalvoidput(Stringkey,ViewModelviewModel){ViewModeloldViewModel=mMap.put(key,viewModel);if(oldViewModel!=null){oldViewModel.onCleared();}}finalViewModelget(Stringkey){returnmMap.get(key);}Set<String>keys(){returnnewHashSet<>(mMap.keySet());}/** * Clears internal storage and notifies ViewModels that they are no longer used. */publicfinalvoidclear(){for(ViewModelvm:mMap.values()){vm.clear();}mMap.clear();}}
//创建ViewModelStore 该方法有2处调用voidensureViewModelStore(){if(mViewModelStore==null){NonConfigurationInstancesnc=(NonConfigurationInstances)getLastNonConfigurationInstance();if(nc!=null){// Restore the ViewModelStore from NonConfigurationInstancesmViewModelStore=nc.viewModelStore;}if(mViewModelStore==null){mViewModelStore=newViewModelStore();}}}
publicViewModelStoregetViewModelStore(){if(getApplication()==null){thrownewIllegalStateException("Your activity is not yet attached to the "+"Application instance. You can't request ViewModel before onCreate call.");}ensureViewModelStore();returnmViewModelStore;}