前言
前面上一篇讲解了LiveData,这一篇我们就讲讲和LiveData组件经常结合使用的ViewModel。
学习ViewModel之前首先我们得简单了解下MVP和MVVM,因为ViewModel是MVVM中的一个元素。
MVP
MVVM
onChanged()
方法,从而更新UI, 这个过程是系统源码帮我们处理的,所以就没有上面Presenter中调用View的那一步了。onSaveInstanceState()
方法从 onCreate()
中的捆绑包恢复其数据,但此方法仅适合可以序列化再反序列化的少量数据,而不适合数量可能较大的数据,如用户列表或位图,使用ViewModel可以解决这个问题。ViewModel
的使用比较简单,我们想要使用使用的话直接继承ViewModel
或者继承AndroidViewModel
即可,AndroidViewModel
源码如下,他们俩的区别,是AndroidViewModel中多了一个Application
的成员变量以及以Application
为参数的构造方法,如果你需要Application
的话,就直接继承AndroidViewModel
即可。public class AndroidViewModel extends ViewModel {
@SuppressLint("StaticFieldLeak")
private Application mApplication;
public AndroidViewModel(@NonNull Application application) {
mApplication = application;
}
/**
* Return the application.
*/
@SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"})
@NonNull
public <T extends Application> T getApplication() {
return (T) mApplication;
}
}
AppsViewModel
如下:class AppsViewModel(appsRepository: AppsRepository) : ViewModel() {
val apps: LiveData<List<AppEntity>> = appsRepository.loadApps()
}
class AppsViewModelFactory(private val repository: AppsRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return AppsViewModel(repository) as T
}
}
class AppsListFragment : Fragment() {
private lateinit var viewModel: AppsViewModel
//-----1-----
private val viewModel: AppsViewModel by viewModels {
FactoryProvider.providerAppsFactory(requireContext())
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
//-----2-----
viewModel = ViewModelProviders.of(this,FactoryProvider.providerAppsFactory(requireContext()))
.get(AppsViewModel::class.java)
//-----3-----
viewModel.apps.observe(viewLifecycleOwner, Observer {
//Update UI
})
}
}
viewModel
,我们可以通过注释1处的 by viewModels
提供一个自定义的Factory,但是需要添加一个依赖:implementation "androidx.fragment:fragment-ktx:1.2.2
;或者采用注释2的方式直接使用ViewModelProviders.of(fragment,factory).get(class)
的形式获取实例。viewmodel.apps.observe
将其加入生命周期观察中,如果数据发生变化就会调用Observer的回调,从而更新UI。ViewModelProviders.of(...).get(class)
方法获取ViewModel,我们就从这里开始源码开始分析,我们先看下这个类的源码:@Deprecated
public class ViewModelProviders {
@Deprecated
public ViewModelProviders() {
}
@Deprecated
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull Fragment fragment) {
return new ViewModelProvider(fragment);
}
@Deprecated
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity) {
return new ViewModelProvider(activity);
}
@Deprecated
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull Fragment fragment, @Nullable Factory factory) {
if (factory == null) {
factory = fragment.getDefaultViewModelProviderFactory();
}
return new ViewModelProvider(fragment.getViewModelStore(), factory);
}
@Deprecated
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity,
@Nullable Factory factory) {
if (factory == null) {
factory = activity.getDefaultViewModelProviderFactory();
}
return new ViewModelProvider(activity.getViewModelStore(), factory);
}
@SuppressWarnings("WeakerAccess")
@Deprecated
public static class DefaultFactory extends ViewModelProvider.AndroidViewModelFactory {
@Deprecated
public DefaultFactory(@NonNull Application application) {
super(application);
}
}
}
NewInstanceFactory
来作为Factory的,看到内部的create方法通过反射生成了一个ViewModel,实例源码如下:public static class NewInstanceFactory implements Factory {
private static NewInstanceFactory sInstance;
/**
* Retrieve a singleton instance of NewInstanceFactory.
*
* @return A valid {@link NewInstanceFactory}
*/
@NonNull
static NewInstanceFactory getInstance() {
if (sInstance == null) {
sInstance = new NewInstanceFactory();
}
return sInstance;
}
@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);
}
}
}
of
方法调用结束返回的是ViewModelProvider
, 然后调用的是get
方法,我们看下这个类的部分源码:public class ViewModelProvider {
private static final String DEFAULT_KEY ="androidx.lifecycle.ViewModelProvider.DefaultKey";
private final Factory mFactory;
private final ViewModelStore mViewModelStore;
//-----1-----
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;
}
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);
}
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
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);
}
mViewModelStore.put(key, viewModel);
return (T) viewModel;
}
}
ViewModelProvider
最重要的方法了,我们先看此类中有两个重要的成员变量,其中一个是mFactory
, 注释1处看到如果我们没有传入factory的话,默认实现的是NewInstanceFactory
, 印证了我们之前的说法。还有一个是ViewModelStore
, 它是怎么来的呢?因为ComponentActivity
中实现了接口ViewModelStoreOwner
,在ViewModelProvider
的构造方法中调用owner.getViewModelStore()
,这个owner
就是ComponentActivity
自身,然后获取到了ViewModelStore
这个变量,实际调用的源码如下:@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.");
}
//-----1-----
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;
}
mViewModelStore == null
的话,就会调取getLastNonConfigurationInstance
尝试获取,如果获取到了就将获取到的赋值给mViewModelStore
返回。这里就涉及到一个重要的知识点了,为什么说ViewModel在横竖屏切换的时候能够持久的保存数据,不需要像之前一样调用onSaveInstanceState
? 因为在Activity被销毁的时候,还会调用另外一个方法onRetainNonConfigurationInstance
, 我们看它在ComponentActivity
中的源码实现: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;
}
//----1-----
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
viewModelStore
存储到NonConfigurationInstances
中了,然后在调用getViewModelStore
的时候调用getLastNonConfigurationInstance
这样就保证了Activity销毁之前和之后的viewModelStore
是同一个,那它里面存储的ViewModel值也就是同样的了。所以ViewModel的生命周期可以用下图来概括:get
方法:private static final String DEFAULT_KEY =
"androidx.lifecycle.ViewModelProvider.DefaultKey"
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);
}
DEFAULT_KEY
拼凑成一个Key,然后调用get
的重载方法如下:public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
ViewModel viewModel = mViewModelStore.get(key);
//-----1-----
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 {
//-----2-----
viewModel = (mFactory).create(modelClass);
}
mViewModelStore.put(key, viewModel);
return (T) viewModel;
}
modelClass
是不是属于ViewModel类型的,并且判断mFactory的类型是否属于OnRequeryFactory
类型,如果是的话,就返回值;viewModel
, 然后将其存入mViewModelStore
中。我们看下ViewModelStore
的源码: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();
}
}
ViewModelStore
的源码很简单,内部持有了一个HashMap对象,用来存放ViewModel。ViewModel的创建到此就结束了。然后就是使用的问题, 使用如下。override fun onActivityCreated(savedInstanceState: Bundle?) {
viewModel = ViewModelProviders.of(this,FactoryProvider.providerAppsFactory(requireContext()))
.get(AppsViewModel::class.java)
viewModel.apps.observe(viewLifecycleOwner, Observer {
//Update UI
})
}