一、ViewModel介绍
ViewModel 作为 Jetpack 组件库首屈一指的高频组件之一,ViewModel 类旨在以注重生命周期的方式存储和管理界面相关的数据。ViewModel 类让数据可在发生屏幕旋转等配置更改后继续留存。它的出现释放了 Activity/Fragment 管理数据的压力,ViewModel 经常会搭配 LiveData 一起用于 MVVM 的开发模式。
Tips:配置变更主要是指:横竖屏切换、分辨率调整、权限变更、系统字体样式变更…
Google ViewModel 文档
二、ViewModel引入工程
implementation :'androidx.appcompat:appcompat:1.2.0'
//或者
implementation :'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
三、核心类和使用方法介绍
存储的数据只能当页面因为配置变更导致的销毁再重建时可复用,复用的是 ViewModel 的实例对象整体:
class MainActivity : AppCompatActivity() {
private val myViewModel by lazy {
ViewModelProvider(this).get(MyViewModel::class.java).apply {
nameLiveData.observe(this@MainActivity, {
})
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
class MyViewModel : ViewModel() {
val nameLiveData = MutableLiveData()
override fun onCleared() {
super.onCleared()
Log.e("MyViewModel", "onCleared")
}
}
五、实现原理源码分析
ViewModelProvider
构造器 参数为 宿主的ViewModelStore
(HasMap) 和 Factory
(创建ViewModel实例使用)
private static final String DEFAULT_KEY =
"androidx.lifecycle.ViewModelProvider.DefaultKey";
private final Factory mFactory;
private final ViewModelStore mViewModelStore;
public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
: NewInstanceFactory.getInstance());
}
public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
this(owner.getViewModelStore(), factory);
}
public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
mFactory = factory;
mViewModelStore = store;
}
NewInstanceFactory
默认工厂方法 通过class反射创建ViewModel实例 优化:(如果自定义实现 Factory 重写create 方法 可以以new的方式创建ViewModel 对象 )
public static class NewInstanceFactory implements Factory {
private static NewInstanceFactory sInstance;
@NonNull
static NewInstanceFactory getInstance() {
if (sInstance == null) {
sInstance = new NewInstanceFactory();
}
return sInstance;
}
@SuppressWarnings("ClassNewInstance")
@NonNull
@Override
public T create(@NonNull Class modelClass) {
//noinspection TryWithIdenticalCatches
try {
return modelClass.newInstance();//通过反射创建
} catch (InstantiationException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
}
}
}
创建ViewModel 实例
@NonNull
@MainThread
public T get(@NonNull Class modelClass) {
String canonicalName = modelClass.getCanonicalName();
if (canonicalName == null) {
throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
}
//key生成规则
return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
}
@NonNull
@MainThread
public T get(@NonNull String key, @NonNull Class modelClass) {
//从map 中获取
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);//通过Factory 创建ViewModel对象
}
//保存到map 里面
mViewModelStore.put(key, viewModel);
return (T) viewModel;
}
getViewModelStore
ViewModel 实例对象不随着宿主重建而销毁,那就要保证 ViewModelStore 实例对象不随着宿主重建而销毁
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner{
private ViewModelStore mViewModelStore;
@NonNull
@Override
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来获取ViewModelStore实例对象,
//如果不为空那是不是就能做到复用了 ?
//所以重点在于ViewModelStore何时被存储到NonConfigurationInstances里面的.
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
//这时候被创建了 说明没有activity或者fragment 是第一次正常启动
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
}
NonConfigurationInstances
Activity内部的一个静态类 该方法就用于获取非配置项实例,以便在后续重建 Activity 时恢复数据
因系统原因页面被回收时,会触发该方法,所以 viewModelStore 对象此时会被存储在NonConfigurationInstance 中。在页面恢复重建时,会再次把这个 NonConfigurationInstance 对象传递到新的Activity 中实现对象复用
扩展 :可以重写onRetainCustomNonConfigurationInstance 方法来保存我们自己的自定义数据状态 并在activity 重建的时候恢复使用 但是google 已经把该方法标记为已弃用 并且注释:Use a {@link androidx.lifecycle.ViewModel} if you want to retain your own non config state.(你的任何数据状态应该保存在ViewModel 中)
public class ComponentActivity{
static final class NonConfigurationInstances {
Object custom;
ViewModelStore viewModelStore;
}
/**
* Retain all appropriate non-config state. You can NOT
* override this yourself! Use a {@link androidx.lifecycle.ViewModel} if you want to
* retain your own non config state.
*/
//保留所有适当的非配置状态。 你不能自己重写
@Override
@Nullable
public final Object onRetainNonConfigurationInstance() {
//需要自定义保存数据状态 以便在页面恢复的时候使用 重写该函数
Object custom = onRetainCustomNonConfigurationInstance();
ViewModelStore viewModelStore = mViewModelStore;
if (viewModelStore == null) {
// No one called getViewModelStore(), so see if there was an existing
// ViewModelStore from our last NonConfigurationInstance
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
viewModelStore = nc.viewModelStore;
}
}
//没有 viewModel 和自定义状态的情况就不用保存数据状态了
if (viewModelStore == null && custom == null) {
return null;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
}
retainNonConfigurationInstances
配置变更时 该方法用于回调 Activity
的 onDestroy
方法,在回调前会先将数据保存到 ActivityClientRecord
的 lastNonConfigurationInstances
字段中
public class Activity{
NonConfigurationInstances mLastNonConfigurationInstances;
static final class NonConfigurationInstances {
Object activity;
HashMap children;
FragmentManagerNonConfig fragments;
ArrayMap loaders;
VoiceInteractor voiceInteractor;
}
NonConfigurationInstances retainNonConfigurationInstances() {
//activity里面有ViewModelStore实例
Object activity = onRetainNonConfigurationInstance();
HashMap 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 loaders = mFragments.retainLoaderNonConfig();
if (activity == null && children == null && fragments == null && loaders == null
&& mVoiceInteractor == null) {
return null;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.activity = activity;//保存到NonConfigurationInstances对象中
nci.children = children;
nci.fragments = fragments;
nci.loaders = loaders;
if (mVoiceInteractor != null) {
mVoiceInteractor.retainInstance();
nci.voiceInteractor = mVoiceInteractor;
}
return nci;
}
}
ActivityThread
在 ActivityThread 类的以下方法存在调用,该方法用于回调 Activity 的 onDestroy 方法,在回调前会先将数据保存到 ActivityClientRecord 的 lastNonConfigurationInstances 字段中
在重新启动 Activity 时,又会将数据 attach 到新的 Activity 实例上,将其作为 getLastNonConfigurationInstance() 方法的返回值,从而完成了数据的交接
public final class ActivityThread{
//ArrayMap 来保存activtiy 的状态数据
final ArrayMap mActivities = new ArrayMap<>();
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
···
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
···
//将 r.lastNonConfigurationInstances 传递进去 恢复数据
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.configCallback,
r.assistToken);
···
return activity;
}
//Activity Destory 的时候被调用 会判断是否因配置该变被调用 并保存Activity 状态数据
ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
int configChanges, boolean getNonConfigInstance, String reason) {
ActivityClientRecord r = mActivities.get(token);
···
if (getNonConfigInstance) {//配置该变被调用
try {
//保存 Activity 返回的 NonConfigurationInstances
r.lastNonConfigurationInstances
= r.activity.retainNonConfigurationInstances();
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException(
"Unable to retain activity "
+ r.intent.getComponent().toShortString()
+ ": " + e.toString(), e);
}
}
}
···
//调用 Activity 的 onDestroy 方法
mInstrumentation.callActivityOnDestroy(r.activity);
···
return r;
}
}
重新启动 Activity 时,又会将数据 attach 到新的 Activity 实例上,将其作为 getLastNonConfigurationInstance() 方法的返回值,从而完成了数据的交接
public class Activity{
// NonConfigurationInstances 保存的ViewModel的对象实例
NonConfigurationInstances mLastNonConfigurationInstances;
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) {
...
//数据恢复
mLastNonConfigurationInstances = lastNonConfigurationInstances;
...
}
public Object getLastNonConfigurationInstance() {
return mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.activity : null;
}
}
public class ComponentActivity implements ViewModelStoreOwner{
@NonNull
@Override
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) {
// 从Activtiy NonConfigurationInstances获取viewModel实例
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
}|
viewModel 在宿主生命周期DESTROY的时候 做释放清理工作
public ComponentActivity() {
Lifecycle lifecycle = getLifecycle();
//noinspection ConstantConditions
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
//在不是配置变更的情况下
if (!isChangingConfigurations()) {
// 最终会调用ViewModel.onCleared
getViewModelStore().clear();
}
}
}
});
}
五、ViewModel总结
页面配置更改数据不丢失
当设备因配置更改导致 Activity/Fragment 重建,ViewModel 中的数据并不会因此而丢失,配合 LiveData 可以在页面重建后立马能收到最新保存的数据用以重新渲染页面
生命周期感应
在 ViewModel 中难免会做一些网络请求或数据的处理,可以复写 onCleared() 方法,终止清理一些操作,释放内存。该方法在宿主 onDestroy 时被调用
数据共享
对于单 Activity 对多 Fragment 的页面,可以使用 ViewModel 实现页面之间的数据共享,实际上不同的 Activity也可以实现数据共享。
六、ViewModel 和 onSaveIntanceState 区别
onSaveIntanceState
只能存储轻量级的 key-value 键值对数据,非配置变更导致的页面被回收时才会触发,此时数据存储在ActivityRecord
中。ViewModel 可以存放任意 Object 数据,因配置变更导致的页面被回收才有效。保存在ActivityThread#ActivityClientRecord 中。