Android MVVM 解读 3. Android MVVM 介绍(3) ViewModel

2.4 ViewModel

官方介绍 ViewModel Overview

  • Implement a ViewModel

  • The lifecycle of a ViewModel

  • Share data between fragments

  • Replacing Loaders with ViewModel

  • Use coroutines with ViewModel

  • Use coroutines with ViewModel

  • Further information

  • Additional resources

Saving UI States

  • User expectations and system behavior
  • Options for preserving UI state
  • Use ViewModel to handle configuration changes
  • Use onSaveInstanceState() as backup to handle system-initiated process death
  • Use local persistence to handle process death for complex or large data

ViewModels: Persistence, onSaveInstanceState(), Restoring UI State and Loaders

Saved State module for ViewModel

2.4.1 理解

1. 官方解释

  1. 此类设计出来,是用于与存储和管理UI相关的数据; 并且允许数据正在configuration changes 例如屏幕旋转时,数据不改变;
  2. UI控制器需要管理异步的请求, 保证系统会在他们销毁时,及时清理他们,避免潜在的内存泄漏,这种管理是需要很多的维护工作, 例如在configuration change时,对象会涉及到重建, 但是这样是浪费系统的资源的, 因为对象可能不得不重新发出他已经发出的调用

2. 个人理解

  1. ViewModel是AMS系统级别支持的对象, 在ui经历 configuration changes 或者onSaveInstanceState时, ViewModel 有比较友好的功能, 能够方便在内存级别恢复ViewModel
  2. ViewModel 从事的是与UI相关的逻辑, 而具体的有关数据存储层和缓存的操作,需要在Model层,即安卓推荐的Repository的层面实现

3. Demo

Implement a ViewModel

The lifecycle of a ViewModel

Share data between fragments

2.4.2 类图

android-mvvm-viewmodel.png

相关的类介绍

根据在MVVM常用的Demo中的用法,从ViewModelProviders中,通过参数Factory和当前的ui对象,Activity或者Fragment,获取到ViewModelProvider, Factory用于构造ViewModel,而ViewModelStore是用于存储ViewModel的对象,在onConfigurationChange时, 是可以从当前的Fragment或者Activity中直接恢复的.

mViewModel = ViewModelProviders.of(this).get(ScoreViewModel.class);

这行代码,便是获取ViewModel的常用方法, 我们查看源码,便可以看到相关的类和逻辑

查看前,可以先看下这个序列图

MVVM ViewModel Sequence.png

1. ViewModelProviders.of(FragmentActivity activity)源码

/**
 * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity
 * is alive. More detailed explanation is in {@link ViewModel}.
 * 

* It uses {@link ViewModelProvider.AndroidViewModelFactory} to instantiate new ViewModels. * * @param activity an activity, in whose scope ViewModels should be retained * @return a ViewModelProvider instance */ @NonNull @MainThread public static ViewModelProvider of(@NonNull FragmentActivity activity) { return of(activity, null); } /** * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity * is alive. More detailed explanation is in {@link ViewModel}. *

* It uses the given {@link Factory} to instantiate new ViewModels. * * @param activity an activity, in whose scope ViewModels should be retained * @param factory a {@code Factory} to instantiate new ViewModels * @return a ViewModelProvider instance */ @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(ViewModelStores.of(activity), factory); }

ViewModelProviders 是一个工具类, 用于方便开发者构建相关的ViewModelProvider,ViewMode在构建时,有两个关键的参数, Factory和ViewModelStores, ViewModelStores用于存储, Factory用于在首次构建时,没有的情况下,生产ViewModel

ViewModelStores的设计思路与ViewModelProviders的设计思路一样, 一个工具类

2. ViewModelProviders.of(@NonNull FragmentActivity activity)

/**
* Returns the {@link ViewModelStore} of the given activity.
*
* @param activity an activity whose {@code ViewModelStore} is requested
* @return a {@code ViewModelStore}
*/
@NonNull
@MainThread
public static ViewModelStore of(@NonNull FragmentActivity activity) {
if (activity instanceof ViewModelStoreOwner) {
    return ((ViewModelStoreOwner) activity).getViewModelStore();
}
return holderFragmentFor(activity).getViewModelStore();
}

正常来讲, Activity/Fragment会作为ViewModelStoreOwner, 在Activity/Fragment中持有这个ViewModelStore,这样ViewModelStore和Activity绑定在一起了.Activity有特殊的处理,针对onConfigurationChange时, activityManagerService会存储这个信息,然后再次分发给Activity.onCreate.便重新恢复了ViewModelStore.

3. ViewModelProvider.get(@NonNull Class modelClass)

 /**
* Returns an existing ViewModel or creates a new one in the scope (usually, a fragment or
* an activity), associated with this {@code 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 modelClass The class of the ViewModel to create an instance of it if it is not * present. * @param The type parameter for the ViewModel. * @return A ViewModel that is an instance of the given type {@code T}. */ @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"); } return get(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 {@code 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. * @param The type parameter for the ViewModel. * @return A ViewModel that is an instance of the given type {@code T}. */ @NonNull @MainThread public T get(@NonNull String key, @NonNull Class 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. } } viewModel = mFactory.create(modelClass); mViewModelStore.put(key, viewModel); //noinspection unchecked return (T) viewModel; }

首次ViewModel的查找,会从ViewModelStore中查找,如果存在,便直接返回, 如果不存在,通过Factory生成.Factory默认是通过反射生成的.这个Factory可继承,然后不使用反射,而是用普通的new的方法构造.

2.4.3 总结

ViewModel的作用.

  1. View的逻辑层, 和数据的提供者(实际为Model), Model将底层数据或者网络数据,通过ViewModel转为实际的View可检测的数据
  2. ViewModel 由于可以在onConfigurationChange被合理的处理,不需要再次销毁重建,因而方便了使用.

你可能感兴趣的:(Android MVVM 解读 3. Android MVVM 介绍(3) ViewModel)