ViewModel简介
ViewModel是通过关联生命周期的方式来存储和管理跟UI相关的数据。即使configuration发生变化,在viewModel中存放的数据是不会被销毁的
没有使用ViewModel的时候,如果系统configuration发生变化,我们的Activity会被销毁重建,导致Activity中的UI数据丢失。为了规避这个问题,我们只能在onSaveInstanceState()将UI数据进行保存,在onCreate方法中判断saveInstanceState中是否有我们存储的数据。
有了ViewModel之后,我们只需要将数据存储到ViewModel即可,ViewModel中的数据不会随着Activity的销毁重建而消失。同时,如果不同的Fragment使用相同的Activity对象来获取ViewModel,可以轻易的实现数据共享和通信。
// 自定义一个ViewModel,存储一个字符串
public class TestViewModel extends ViewModel {
public String content;
@Override
protected void onCleared() {
// 数据清理工作
content = null;
}
}
// 在Activity中获取并使用ViewModel
TestViewModel viewModel = ViewModelProviders.of(activity).get(TestViewModel.class);
Log.d("tag", viewModel.content);
三个问题
1.ViewModel是如何创建出来的?
2.为什么不同的Fragment使用相同的Activity对象来获取ViewModel,可以轻易的实现ViewModel共享?
3.ViewModel为什么在Activity销毁重建时不会被销毁回收?
源码分析
问题1.ViewModel是如何创建出来的?
通过示例代码,去掉链式调用后,我们可以看到ViewModel是通过如下两步创建出来的:
//1.创建ViewModelProvider
ViewModelProvider viewModelProvider=ViewModelProviders.of(activity);
//2.通过反射获取ViewModel
TestViewModel viewModel=viewModelProvider.get(TestViewModels.class);
创建ViewModelProvider
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity,
@Nullable Factory factory) {
Application application = checkApplication(activity);
if (factory == null) {
factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
}
return new ViewModelProvider(activity.getViewModelStore(), factory);
}
源码中,我们发现创建一个ViewModelProvider需要传入两个参数:ViewModelStore和Factory。我们先看下Factory的实现
Factory
Factory顾名思议 定义了创建ViewModel的行为接口。里面只有一个create方法,用于子类自行决定如何实现一个ViewModel对象的创建
/**
* Implementations of {@code Factory} interface are responsible to instantiate ViewModels.
*/
public interface Factory {
/**
* Creates a new instance of the given {@code Class}.
* <p>
*
* @param modelClass a {@code Class} whose instance is requested
* @param <T> The type parameter for the ViewModel.
* @return a newly created ViewModel
*/
@NonNull
<T extends ViewModel> T create(@NonNull Class<T> modelClass);
}
同时,ViewModelProvider源码内部也提供了两个默认Factory实现:NewInstanceFactory和AndroidViewModelFactory。
//直接反射class对象的无参构造函数来创建ViewModel
/**
* Simple factory, which calls empty constructor on the give class.
*/
public static class NewInstanceFactory implements Factory {
@SuppressWarnings("ClassNewInstance")
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> 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);
}
}
}
//1.如果对象集成自AndroidViewModel,调用带Application参数的构造函数创建ViewModel对象
//2.如果对象不继承自AndroidViewModel,则直接调用父类,即调用class的无参构造函数创建ViewModel对象
/**
* {@link Factory} which may create {@link AndroidViewModel} and
* {@link ViewModel}, which have an empty constructor.
*/
public static class AndroidViewModelFactory extends ViewModelProvider.NewInstanceFactory {
private static AndroidViewModelFactory sInstance;
/**
* Retrieve a singleton instance of AndroidViewModelFactory.
*
* @param application an application to pass in {@link AndroidViewModel}
* @return A valid {@link AndroidViewModelFactory}
*/
@NonNull
public static AndroidViewModelFactory getInstance(@NonNull Application application) {
if (sInstance == null) {
sInstance = new AndroidViewModelFactory(application);
}
return sInstance;
}
private Application mApplication;
/**
* Creates a {@code AndroidViewModelFactory}
*
* @param application an application to pass in {@link AndroidViewModel}
*/
public AndroidViewModelFactory(@NonNull Application application) {
mApplication = application;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if (AndroidViewModel.class.isAssignableFrom(modelClass)) {
//noinspection TryWithIdenticalCatches
try {
return modelClass.getConstructor(Application.class).newInstance(mApplication);
} catch (NoSuchMethodException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (InstantiationException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Cannot create an instance of " + modelClass, e);
}
}
return super.create(modelClass);
}
}
启示:我们自定义的ViewModel对象如果构造函数中需要其他各种参数,我们只需要创建一个自定义的Factory类,然后调用该class的有参构造函数进行创建即可。
ViewModelStore
ViewModelStore就是个HashMap,通过key来获取ViewModel对象
public class ViewModelStore {
private final HashMap<String, ViewModel> mMap = new HashMap<>();
final void put(String key, ViewModel viewModel) {
ViewModel oldViewModel = mMap.put(key, viewModel);
if (oldViewModel != null) {
oldViewModel.onCleared();
}
}
final ViewModel get(String key) {
return mMap.get(key);
}
Set<String> keys() {
return new HashSet<>(mMap.keySet());
}
/**
* Clears internal storage and notifies ViewModels that they are no longer used.
*/
public final void clear() {
for (ViewModel vm : mMap.values()) {
vm.clear();
}
mMap.clear();
}
}
ViewModelProvider
了解Factory实现和ViewModelStore实现后,我们来看一下ViewModelProvider的get方法如何创建ViewModel对象的
public class ViewModelProvider {
private static final String DEFAULT_KEY =
"androidx.lifecycle.ViewModelProvider.DefaultKey";
private final Factory mFactory;
private final ViewModelStore mViewModelStore;
public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
this(owner.getViewModelStore(), factory);
}
public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
mFactory = factory;
mViewModelStore = store;
}
@NonNull
@MainThread
public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {
String canonicalName = modelClass.getCanonicalName();
if (canonicalName == null) {
throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
}
return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
}
@NonNull
@MainThread
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
ViewModel viewModel = mViewModelStore.get(key);
if (modelClass.isInstance(viewModel)) {
//noinspection unchecked
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);
}
mViewModelStore.put(key, viewModel);
//noinspection unchecked
return (T) viewModel;
}
}
ViewModelProvider的get方法实现也必将简单,总结一下就是:
1.使用ViewModelClass的canonicalName作为ViewModel在ViewModelSotre中的唯一标识
2.通过唯一标识,先查询一下ViewModelStore中是否有该ViewModel对象,如果有则直接返回
3.如果ViewModel中没有该ViewModel对象,则通过Factory工厂类反射创建出ViewModel对象,存入ViewModelStore中,并返回给调用者。
问题2.为什么不同的Fragment使用相同的Activity对象来获取ViewModel,可以轻易的实现ViewModel共享?
因为不同的Fragment使用相同的Activity对象来获取ViewModel,在创建ViewModel之前都会先从Activity提供的ViewModelStore中先查询一遍是否已经存在该ViewModel对象。所以我们只需要先在Activity中同样调用一遍ViewModel的获取代码,即可让ViewModel存在于ViewModelStore中,从而不同的Fragment可以共享一份ViewModel了。
问题3.ViewModel为什么在Activity销毁重建时不会被销毁回收?
在看这个问题之前,我们回到ViewModelProviders.of()源码中:
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity,
@Nullable Factory factory) {
Application application = checkApplication(activity);
if (factory == null) {
factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
}
return new ViewModelProvider(activity.getViewModelStore(), factory);
}
ViewModelProvider获取ViewModelStore对象是同过activity.getViewModelStore()实现的
源码如下:
@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) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
通过源码发调用了getLastNonConfigurationInstance() 方法 返回
NonConfigurationInstances 对象,如果该对象不为空 拿到这个对象中保存的ViewModelStore对象 返回。 那么 NonConfigurationInstances 对象什么时候赋值的?通过源码发现
/**
* 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;
}
}
if (viewModelStore == null && custom == null) {
return null;
}
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
通过源码发现原来是onRetainNonConfigurationInstance()这个而生命周期方法里面调用了保存了ViewModelStore对象
onRetainNonConfigurationInstance的作用:大部分同学知道Activity因为configuration变化销毁和重建时会调用onSaveInstanceState和onRestoreInstanceState。与此同时,Activity其实还会回调onRetainNonConfigurationInstance和getLastNonConfigurationInstance方法。
onRetainNonConfigurationInstance和onSaveInstanceState作用相同,用来保存UI相关变量,当Activity意外销毁时,Activity的ViewModelStore对象就是在这里进行了保存,所以通过以上分析,我们终于知道了,为何Activity因为意外销毁时,ViewModelStore不会被销毁回收。
小结
这里我们学到了Activity的两个跟生命周期相关的函数调用:onRetainNonConfigurationInstance和getLastNonConfigurationInstance。
1.Activity实现了ViewModelStoreOwner接口,创建了ViewModelStore对象。
2.当Activity意外销毁时,onRetainNonConfigurationInstance函数被回调,在此函数中对ViewModelStore对象进行了保存。
3.当Activity重建时,onCreate方法中会先获取getLastNonConfigurationInstance,如果其中的ViewModelStore对象不为空,就直接引用,不再重新创建ViewModelStore对象了。