privateval mViewModel by lazy { ViewModelProvider(this)[TestViewModel::class.java] }
我们把当前的activity传进了ViewmodelProvider的构造函数,我们看一看
/** * Creates `ViewModelProvider`. This will create `ViewModels` * and retain them in a store of the given `ViewModelStoreOwner`. * * * This method will use the * [default factory][HasDefaultViewModelProviderFactory.getDefaultViewModelProviderFactory] * if the owner implements [HasDefaultViewModelProviderFactory]. Otherwise, a * [NewInstanceFactory] will be used. */ publicconstructor( owner: ViewModelStoreOwner ) : this(owner.viewModelStore, defaultFactory(owner), defaultCreationExtras(owner))
/** * Creates `ViewModelProvider`, which will create `ViewModels` via the given * `Factory` and retain them in a store of the given `ViewModelStoreOwner`. * * @param owner a `ViewModelStoreOwner` whose [ViewModelStore] will be used to * retain `ViewModels` * @param factory a `Factory` which will be used to instantiate * new `ViewModels` */ publicconstructor(owner: ViewModelStoreOwner, factory: Factory) : this( owner.viewModelStore, factory, defaultCreationExtras(owner) )
overridefun<T : ViewModel>create(modelClass: Class<T>, extras: CreationExtras): T { val key = extras[ViewModelProvider.NewInstanceFactory.VIEW_MODEL_KEY] ?: throw IllegalStateException( "VIEW_MODEL_KEY must always be provided by ViewModelProvider" )
returnif (extras[SAVED_STATE_REGISTRY_OWNER_KEY] != null && extras[VIEW_MODEL_STORE_OWNER_KEY] != null) { val application = extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] val isAndroidViewModel = AndroidViewModel::class.java.isAssignableFrom(modelClass) valconstructor: Constructor<T>? = if (isAndroidViewModel && application != null) { findMatchingConstructor(modelClass, ANDROID_VIEWMODEL_SIGNATURE) } else { findMatchingConstructor(modelClass, VIEWMODEL_SIGNATURE) } // doesn't need SavedStateHandle if (constructor == null) { return factory.create(modelClass, extras) } val viewModel = if (isAndroidViewModel && application != null) { newInstance(modelClass, constructor, application, extras.createSavedStateHandle()) } else { newInstance(modelClass, constructor, extras.createSavedStateHandle()) } viewModel } else { val viewModel = if (lifecycle != null) { create(key, modelClass) } else { throw IllegalStateException("SAVED_STATE_REGISTRY_OWNER_KEY and" + "VIEW_MODEL_STORE_OWNER_KEY must be provided in the creation extras to" + "successfully create a ViewModel.") } viewModel } }
// it is done instead of getConstructor(), because getConstructor() throws an exception // if there is no such constructor, which is expensive internalfun<T>findMatchingConstructor( modelClass: Class<T>, signature: List<Class<*>> ): Constructor<T>? { for (constructorin modelClass.constructors) { val parameterTypes = constructor.parameterTypes.toList() if (signature == parameterTypes) { @Suppress("UNCHECKED_CAST") returnconstructoras Constructor<T> } if (signature.size == parameterTypes.size && parameterTypes.containsAll(signature)) { throw UnsupportedOperationException( "Class ${modelClass.simpleName} must have parameters in the proper " + "order: $signature" ) } } returnnull }
@MainThread publicopenoperatorfun<T : ViewModel>get(modelClass: Class<T>): T { val canonicalName = modelClass.canonicalName ?: throw IllegalArgumentException("Local and anonymous classes can not be ViewModels") returnget("$DEFAULT_KEY:$canonicalName", modelClass) }
/** * Returns an existing ViewModel or creates a new one in the scope (usually, a fragment or * an activity), associated with this `ViewModelProvider`. * * The created ViewModel is associated with the given scope and will be retained * as long as the scope is alive (e.g. if it is an activity, until it is * finished or process is killed). * * @param key The key to use to identify the ViewModel. * @param modelClass The class of the ViewModel to create an instance of it if it is not * present. * @return A ViewModel that is an instance of the given type `T`. */ @Suppress("UNCHECKED_CAST") @MainThread publicopenoperatorfun<T : ViewModel>get(key: String, modelClass: Class<T>): T { val viewModel = store[key] if (modelClass.isInstance(viewModel)) { (factory as? OnRequeryFactory)?.onRequery(viewModel) return viewModel as T } else { @Suppress("ControlFlowWithEmptyBody") if (viewModel != null) { // TODO: log a warning. } } val extras = MutableCreationExtras(defaultCreationExtras) extras[VIEW_MODEL_KEY] = key // AGP has some desugaring issues associated with compileOnly dependencies so we need to // fall back to the other create method to keep from crashing. returntry { factory.create(modelClass, extras) } catch (e: AbstractMethodError) { factory.create(modelClass) }.also { store.put(key, it) } }
@NonNull @Override public ViewModelStore getViewModelStore() { if (getApplication() == null) { thrownewIllegalStateException("Your activity is not yet attached to the " + "Application instance. You can't request ViewModel before onCreate call."); } ensureViewModelStore(); return mViewModelStore; }
@SuppressWarnings("WeakerAccess")/* synthetic access */ voidensureViewModelStore() { if (mViewModelStore == null) { NonConfigurationInstancesnc= (NonConfigurationInstances) getLastNonConfigurationInstance(); if (nc != null) { // Restore the ViewModelStore from NonConfigurationInstances mViewModelStore = nc.viewModelStore; } if (mViewModelStore == null) { mViewModelStore = newViewModelStore(); } } }
ViewModelStoreviewModelStore= mViewModelStore; if (viewModelStore == null) { // No one called getViewModelStore(), so see if there was an existing // ViewModelStore from our last NonConfigurationInstance NonConfigurationInstancesnc= (NonConfigurationInstances) getLastNonConfigurationInstance(); if (nc != null) { viewModelStore = nc.viewModelStore; } }
/** * Clears internal storage and notifies ViewModels that they are no longer used. */ publicfinalvoidclear() { for (ViewModel vm : mMap.values()) { vm.clear(); } mMap.clear(); } }