附上官网链接:developer.android.google.cn/topic/libra…

ViewModel简介

ViewModel类被设计用来存储和管理UI界面相关的数据生命周期中的意识的方式。ViewModel类允许生存数据配置更改,如屏幕旋转。

Android Jetpack ViewModel由浅入深_UI

存在的意义 (解决痛点)

1. 数据的持久化

eg: 当系统销毁或重新创建UI控制器(ActivityfragmentView等),则您存储在其中的所有与UI相关的瞬时数据都将丢失。 activityonSaveInstanceState()机制可以用来保存和恢复数据。 缺点:此方法仅适用于可以先序列化然后反序列化的少量数据,不适用于潜在的大量数据,例如用户列表或位图。

生命周期.pngViewModel生命周期可以看到,它的生命周期横跨Activity的所有生命周期,包括旋转等出现的重新创建的生命周期,直到 Activity 真正意义上销毁后才会结束。这样子数据存储在ViewModel中时,便可以保证在生命周期中数据不会丢失

2. UI控制器(Activity、fragment等)异步调用,导致的潜在内存泄漏

面对请求网络、读取IO、或者操作数据库等异步操作,有些操作相当耗时,在UI控制器中我们设置这些回调等待结果,有可能在UI控制器销毁的时候才返回。

ViewModel中处理数据的回调,当Activity销毁的时候,ViewModel也会跑onCleared()清理数据 这样子就不会存在Activity内存泄漏的问题。

3.分担UI控制器的负担

类似MVP中的P层,MVVM中VM存在意义就是替UI 控制器减轻负担。UI控制器只用于相应用户操作,展示数据,将具体的数据逻辑操作(eg:加载网络、数据库数据...等)放到VM层做处理。分工更加明确,也方便测试。

4.在Fragment之间共享数据

比如Activity在两或多个Fragment中,你使用一个Fragment跟另外的Fragment通信,常见的操作是定义接口在Activity中根据接口返回逻辑调用到另外的Fragmet,也有其他可以用EventBus 广播等其它的处理方式,但是前者耦合度高,后者也是相对繁琐

ViewModel中,你可以获取同一个Activity绑定的ViewModel并监听数据的变化 进而实现通信 下面是官网的例子

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

class MasterFragment : Fragment() {

    private lateinit var itemSelector: Selector

    private lateinit var model: SharedViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        model = activity?.run {
            ViewModelProviders.of(this)[SharedViewModel::class.java]
        } ?: throw Exception("Invalid Activity")
        itemSelector.setOnClickListener { item ->
            // Update the UI
        }
    }
}

class DetailFragment : Fragment() {

    private lateinit var model: SharedViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        model = activity?.run {
            ViewModelProviders.of(this)[SharedViewModel::class.java]
        } ?: throw Exception("Invalid Activity")
        model.selected.observe(this, Observer<Item> { item ->
            // Update the UI
        })
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.

好处:

  1. Activity不需要知道两者间的交互也不需要做什么,解耦
  2. Fragment 不需要判断对方是否存在等问题,也不需要持有对方的引用,不影响本身的任何工作,对其生命周期无感。

重点关注的点!!! 在ViewModel中不要持有Activity的引用在ViewModel中不要持有Activity的引用在ViewModel中不要持有Activity的引用 (重要的事情说三遍,因为生命周期比Activity略长 会导致Activity被挟持!!!) 如果需要context对象,可以自行导入Applicationcontext 官方也提供一个含有contextViewModel的子类,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;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

简单使用

  1. 导入库
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:${var}"
  • 1.
  1. 创建子类继承ViewModel()
class NameViewModel :ViewModel(){
    // 创建Livedata的字符串
    val currencyName : MutableLiveData<String> = MutableLiveData()
    val totalMemory : MutableLiveData<String> = MutableLiveData()
    val remainMemory : MutableLiveData<String> = MutableLiveData()

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  1. Activity中使用
class MyActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
//1.先获取一个ViewModel对象
val  mViewModel = ViewModelProviders.of(this).get(NameViewModel::class.java)
//2.定义一个观察者
val nameObserver = Observer<String> { newName ->
   name_text.text = newName
}
//3.通过使用ViewModel对象进行监听
mViewModel.currencyName.observe(this, nameObserver)
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

上面的展示了最基本的使用方式,先获取到mViewModel对象,然后ViewModel.currencyName.observe(this, nameObserver)进行监听Observer<String> { newName -> name_text.text = newName }当数据改变的时候,便会回调监听的内容,并且传入新的newName的值

基础封装

下面对基本项目上用到的ViewModel进行基本的封装 先封装 BaseViewModel BaseActivity (以下的封装只涉及ViewModel,基本的类根据自己的需求进行其他的封装) BaseViewModel

open class BaseViewModel :ViewModel(){
    //处理异常
    val mException:MutableLiveData<Throwable> = MutableLiveData()
}
  • 1.
  • 2.
  • 3.
  • 4.

BaseActivity

open class BaseActivity<VM:BaseViewModel> : AppCompatActivity(), LifecycleObserver {

    lateinit var mViewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        initVM()
        super.onCreate(savedInstanceState)
        startObserver()
    }

    open fun  startObserver(){
    }

    open fun providerVMClass():Class<VM>? = null

    private fun initVM() {
        providerVMClass()?.let {
            mViewModel =  ViewModelProviders.of(this).get(it)
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

使用:

class MainActivity : BaseActivity<NameViewModel>() {
  //提供 NameViewModel
    override fun providerVMClass(): Class<NameViewModel>? = NameViewModel::class.java
    val job = Job()
    val ioScope = CoroutineScope(Dispatchers.IO + job)
    var licycleObserver = MyObserver()

    companion object {
        val TAG = "memory"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_mvvm2)

        initViewModel()
        btn1.setOnClickListener {
            ioScope.launch {
                withContext(Dispatchers.Main) {
                    mViewModel.remainMemory.value = "没有cancel的"
                }
            }
        }
    }

     private fun initViewModel() {

        //获取viewmodel
        mViewModel = ViewModelProviders.of(this).get(NameViewModel::class.java)
        //创建监听 更新UI
        val nameObserver = Observer<String> { newName ->
            name_text.text = newName
        }
        val memoryObserver = Observer<String> { totalMemory ->
            total_memory.text = totalMemory
        }
        val remainMemoryObserver = Observer<String> { remainMemory ->
            remain_memory.text = remainMemory
        }

        mViewModel.currencyName.observe(this, nameObserver)
        mViewModel.totalMemory.observe(this, memoryObserver)
        mViewModel.remainMemory.observe(this, remainMemoryObserver)
    }


}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.

构造器有参数的ViewModel

ViewModel构造函数带有参数的时候,就不能像上面那种实例化,而是要借助ViewModelProviderFatory进行实例化

对上面的ViewModel基础使用改动一波

class NameViewModel(val currencyName:MutableLiveData<String>) :BaseViewModel(){
    // 创建Livedata的字符串

    val totalMemory : MutableLiveData<String> = MutableLiveData()
    val remainMemory : MutableLiveData<String> = MutableLiveData()
  // 创建工厂对象类
    class NameViewModelFactory(private val current:MutableLiveData<String>):ViewModelProvider.NewInstanceFactory(){
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return NameViewModel(current) as T
        }
    }

}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

使用 获取一个ViewModel对象

//1.先获取一个ViewModel对象
ViewModelProviders.of(this,NameViewModel.NameViewModelFactory(MutableLiveData("total"))).get(NameViewModel::class.java)
  • 1.
  • 2.

相比第一次获取实例的方式是调用了ViewModelProvider of(@NonNull FragmentActivity activity, @Nullable Factory factory)增加多了一个工厂对象其它的数据监听跟基本的不带参数实例化ViewModel的用法一致

源码跟踪解读

从最开始的ViewModelProviders.of开始追踪

Android Jetpack ViewModel由浅入深_Android Jetpack_02

从上图可以看到ViewModelProviders主要是用于生成跟返回实例化的ViewModelProvider对象的。

看最本篇文章简单在Activity中使用的时候

val  mViewModel = ViewModelProviders.of(this).get(NameViewModel::class.java)
  • 1.

调用了

public class ViewModelProviders {
  //...省略其他方法
//关键代码1:
  @NonNull
    @MainThread
    public static ViewModelProvider of(@NonNull FragmentActivity activity) {
        return of(activity, null);
    }
//关键代码2:
    @NonNull
    @MainThread
    public static ViewModelProvider of(@NonNull FragmentActivity activity,
            @Nullable Factory factory) {
//关键代码3:
        Application application = checkApplication(activity);

        if (factory == null) {
//关键代码5
            factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
        }
//关键代码6
        return new ViewModelProvider(activity.getViewModelStore(), factory);
    }
//关键代码4:
    private static Application checkApplication(Activity activity) {
        Application application = activity.getApplication();
        if (application == null) {
            throw new IllegalStateException("Your activity/fragment is not yet attached to "
                    + "Application. You can't request ViewModel before onCreate call.");
        }
        return application;
    }
//关键代码7
        @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);
        }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.

可以看到在关键代码2的方法中先是对Activity进行Application判空逻辑(关键代码4 ),我们传进来的factory是空的,则ViewModelProvider.AndroidViewModelFactory.getInstance(application)(关键代码5)获得一个factory,再调用 关键代码6 进而返回一个ViewModelProvider 关键代码7 我们传进来的ViewModel类通过反射的形式创建ViewModel对象并返回 先跟踪关键代码5进去看看factory是怎么来的

public static class AndroidViewModelFactory extends ViewModelProvider.NewInstanceFactory {

        private static AndroidViewModelFactory sInstance;

        public static AndroidViewModelFactory getInstance(@NonNull Application application) {
            if (sInstance == null) {
                sInstance = new AndroidViewModelFactory(application);
            }
            return sInstance;
        }

    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

这里返回了一个单例对象AndroidViewModelFactory

返回上面的 关键代码6 return new ViewModelProvider(activity.getViewModelStore(), factory); 跟踪一下

public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
        mFactory = factory;
        mViewModelStore = store;
    }
  • 1.
  • 2.
  • 3.
  • 4.

这里将mViewModelStoremFactory實例化了 mViewModelStore是从activity.getViewModelStore()得到的

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
    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) {
          //先获取是否存在`ViewModelStore`
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastNonConfigurationInstance();
            if (nc != null) {
                // Restore the ViewModelStore from NonConfigurationInstances
                mViewModelStore = nc.viewModelStore;
            }
            if (mViewModelStore == null) {
              //这里新建了`ViewModelStore`
                mViewModelStore = new ViewModelStore();
            }
        }
        return mViewModelStore;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

看到上面已经生成了ViewModelStore接下来跟踪一下 ViewModelProviders.of(this).get(NameViewModel::class.java)get()方法看看

public class ViewModelProvider {

    private static final String DEFAULT_KEY =
            "androidx.lifecycle.ViewModelProvider.DefaultKey";

    @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);
    }


    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;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.

上面的代码解释一下:先从mViewModelStore.get(key);获取出来ViewModel,如果有则返回,没有的话就调用之前拥有的工厂对象mFactory类去viewModel = (mFactory).create(modelClass)或者((KeyedFactory) (mFactory)).create(key, modelClass) ,最终调用mViewModelStore.put(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());
    }
    public final void clear() {
        for (ViewModel vm : mMap.values()) {
            vm.clear();
        }
        mMap.clear();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

看到上面的代码了吗? 最终返回的viewModel,返回前先调用了mViewModelStore.put(key, viewModel)将这个 viewModel存到mViewModelStore中的HashMap 既然mViewModelStore是存储ViewModel的地方 那我们也看一下ViewModelStore中的clear()是在哪里被调用的

Android Jetpack ViewModel由浅入深_Android Jetpack_03

我们跟踪一下ComponentActivity

getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source,
                    @NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    if (!isChangingConfigurations()) {
                        getViewModelStore().clear();
                    }
                }
            }
        });
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

上面可以看到在Lifecycle.Event.ON_DESTROY为的状态时调用getViewModelStore().clear();方法。也就说在Activity的生命周期到onDestory的时候将本Activity所有的ViewmModel清除掉

这篇文章只是对基本的使用到这个调用的开始到结束,进行源码的一个追踪,对ViewModel有个比较深刻的印象,里面还有很多细节可以考究,只是本人技术有限,如果读者有没什么疑问可以在评论中说一下~