概览
ViewModel
类旨在以注重生命周期的方式存储和管理界面相关数据。ViewModel
类让数据可在发生屏幕旋转等配置更改后继续留存。
ViewModel的生命周期
ViewModel
对象的作用域限定为获取 ViewModel
时传递给 ViewModelProvider
的 ViewModelStoreOwner
的 Lifecycle
。ViewModel
将一直留在内存中,直到其作用域 ViewModelStoreOwner
永久消失:
- 对于 activity,是在 activity 完成时。
- 对于 fragment,是在 fragment 分离时。
- 对于 Navigation 条目,是在 Navigation 条目从返回堆栈中移除时。
这使得 ViewModels 成为了存储在配置更改后仍然存在的数据的绝佳解决方案。
ViewModel原理解析
先看实例化ViewModel
kotlin
private val viewModel :MyViewModel by lazy {
ViewModelProvider(this)[MyViewModel::class.java]
}
可以看到通过ViewModelProvider初始化后的get()方法获取
kotlin
public constructor(
owner: ViewModelStoreOwner
) : this(owner.viewModelStore, defaultFactory(owner), defaultCreationExtras(owner))
public constructor(owner: ViewModelStoreOwner, factory: Factory) : this(
owner.viewModelStore,
factory,
defaultCreationExtras(owner)
)//可以自定义factory,比如我们需要在ViewModel里面传参
可以看到对于我们👆🏻的初始化方式我们传入一个ViewModelStoreOwner
,查看Activity的继承关系到 ComponentActivity就会发现这个Activity实现了 ViewModelStoreOwner
接口,所以初始化的时候我们传入this
。factory是用来创建ViewModel对象的。
kotlin
internal fun defaultFactory(owner: ViewModelStoreOwner): Factory =
if (owner is HasDefaultViewModelProviderFactory)
owner.defaultViewModelProviderFactory else instance
如果是 HasDefaultViewModelProviderFactory
实例,就获取defaultViewModelProviderFactory
,要不就创建NewInstanceFactory
,NewInstanceFacetory是直接通过反射创建ViewModel实例
kotlin
public open class NewInstanceFactory : Factory {
@Suppress("DocumentExceptions")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return try {
modelClass.getDeclaredConstructor().newInstance() //反射创建实例
} catch (e: NoSuchMethodException) {
throw RuntimeException("Cannot create an instance of $modelClass", e)
} catch (e: InstantiationException) {
throw RuntimeException("Cannot create an instance of $modelClass", e)
} catch (e: IllegalAccessException) {
throw RuntimeException("Cannot create an instance of $modelClass", e)
}
}
}
defaultViewModelProviderFactory
则是在Activity中通过如下方法创建获取
less
@NonNull
@Override
public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {
if (mDefaultFactory == null) {
mDefaultFactory = new SavedStateViewModelFactory(
getApplication(),
this,
getIntent() != null ? getIntent().getExtras() : null);
}
return mDefaultFactory;
}
kotlin
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
return if (application != null) {
create(modelClass)
} else {
val application = extras[APPLICATION_KEY]
if (application != null) {
create(modelClass, application)
} else {
// For AndroidViewModels, CreationExtras must have an application set
if (AndroidViewModel::class.java.isAssignableFrom(modelClass)) {
throw IllegalArgumentException(
"CreationExtras must have an application by `APPLICATION_KEY`"
)
}
super.create(modelClass)
}
}
...
}
创建一个带有上下文的AndroidViewModel,然后看下get()方法
kotlin
public open operator fun <T : ViewModel> get(modelClass: Class<T>): T {
val canonicalName = modelClass.canonicalName
?: throw IllegalArgumentException("Local and anonymous classes can not be ViewModels")
return get("$DEFAULT_KEY:$canonicalName", modelClass)
}
kotlin
public open operator fun <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.
}
}
...
从store
中获取
kotlin
open class ViewModelStore {
private val map = mutableMapOf<String, ViewModel>()
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun put(key: String, viewModel: ViewModel) {
val oldViewModel = map.put(key, viewModel)
oldViewModel?.onCleared()
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
operator fun get(key: String): ViewModel? {
return map[key]
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun keys(): Set<String> {
return HashSet(map.keys)
}
fun clear() {
for (vm in map.values) {
vm.clear()
}
map.clear()
}
}
里面维护了一个HashMap,根据Key值对viewmodel进行存储,并提供了clear()方法。
kotlin
public open operator fun <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.
return try {
factory.create(modelClass, extras)
} catch (e: AbstractMethodError) {
factory.create(modelClass)
}.also { store.put(key, it) }
}
获取ViewModelStore
在ViewModelProvider
初始化时会通过 ViewModelStoreOwner
获取ViewModelStore
csharp
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;
}
ini
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();
}
}
}
这里是获取 NonConfigurationInstances
对象,然后获取到 ViewModelStore
,如果 NonConfigurationInstances
为null,则创建ViewModelStore
.看下 getLastNonConfigurationInstance()
方法
typescript
public Object getLastNonConfigurationInstance() {
return mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.activity : null;
}
那这个 mLastNonConfigurationInstances
在哪被赋值?
arduino
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken,
IBinder shareableActivityToken) {
attachBaseContext(context);
mFragments.attachHost(null /*parent*/);
...
mLastNonConfigurationInstances = lastNonConfigurationInstances;//这这============
...
存储ViewModelStore
可以看到是在Activity的attach方法里面被赋值。我们知道在配置更改引起的Activity重建时会调用 onRetainNonConfigurationInstance()
方法
ini
public final Object onRetainNonConfigurationInstance() {
// Maintain backward compatibility.
Object custom = onRetainCustomNonConfigurationInstance();
ViewModelStore viewModelStore = mViewModelStore;
if (viewModelStore == null) {
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
viewModelStore = nc.viewModelStore;
}
}
//1.获取销毁之前的viewModelStore *****************
if (viewModelStore == null && custom == null) {
return null;
}
//2.创建NonConfigurationInstances,赋值viewModelStore ****************
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
现在viewModelStroe
已经被存储在了NonConfigurationInstances
中,页面要销毁,执行ActivityThread的 performDestroyActivity
方法
php
void performDestroyActivity(ActivityClientRecord r, boolean finishing,
int configChanges, boolean getNonConfigInstance, String reason) {
Class<? extends Activity> activityClass = null;
if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
activityClass = r.activity.getClass();
r.activity.mConfigChangeFlags |= configChanges;
if (finishing) {
r.activity.mFinished = true;
}
...
if (getNonConfigInstance) {
try {
r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances(); 3*******
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException("Unable to retain activity "
+ r.intent.getComponent().toShortString() + ": " + e.toString(), e);
}
}
}
...
会调用activity的 retainNonConfigurationInstances()
方法
ini
NonConfigurationInstances retainNonConfigurationInstances() {
Object activity = onRetainNonConfigurationInstance();// 1 ***这块可以获取到刚才封装好的NonConfigurationInstances实例,里面有viewmodelStroe
HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
FragmentManagerNonConfig fragments = mFragments.retainNestedNonConfig();
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(); 2 ******
nci.activity = activity;
nci.children = children;
nci.fragments = fragments;
nci.loaders = loaders;
if (mVoiceInteractor != null) {
mVoiceInteractor.retainInstance();
nci.voiceInteractor = mVoiceInteractor;
}
return nci;
}
总结下上面就是把之前创建的带有viewmodelstroe实例的NonConfigurationInstances
(上面1),在封装到一个NonConfigurationInstances
(上面2),然后保存到ActivityClientRecord
中(上面3)
恢复Viewmodel
然后在页面重建时,调用ActivityThread的 performLaunchActivity
方法
ini
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
...
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.activityConfigCallback,
r.assistToken, r.shareableActivityToken);
if (customIntent != null) {
activity.mIntent = customIntent;
}
...
然后就回到我们刚在说的(可以看到是在Activity的attach方法里面被赋值。)这样从保留NonConfigurationInstances
到保留viewmodelstroe
,最后viewmodel
就被保留了。
最后看下销毁吧
less
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
// Clear out the available context
mContextAwareHelper.clearAvailableContext();
// And clear the ViewModelStore
if (!isChangingConfigurations()) {
getViewModelStore().clear();
}
}
}
});
很简单,通过Lifecycle监听生命周期,然后是非配置更改引起的ON_DESTROY事件,清理viewmodelstore.
总结:
Viewmodel
在配置更改时能保存数据,是因为在Activity
销毁前,调用了retainNonConfigurationInstances()
,将viewmodelstore
存储到了NonConfigurationInstances
对象里,然后在ondestory
又创建了NonConfigurationInstances
在把之前的NonConfigurationInstances
存储进来,最后存储在了ActivityClientRecord
中,在Activity
重建时,通过attach
方法,赋值给 mLastNonConfigurationInstances
,这样最终就可以获取到之前的viewmodel
了