ViewModel 能否在 Activity 保存和恢复后存活下来?

Does ViewModel survive Activity save and restore?

如果以下列方式使用,新 ViewModel class 的实例可以在配置更改后继续存在:

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

但是,除了配置更改之外,还存在整个应用程序进程被终止时的保存-恢复场景。

ViewModel 中的字段值在保存-恢复场景中会被保留吗?


编辑:根据这个问题的回答,写了这篇文章:Android ViewModel Architecture Component is Dangerous

根据 ViewModelProvider 文档(检查 get 方法),当应用进程被终止时 ViewModel 不会被保留:

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)

另外查看 Ian Lake 对类似问题的回答: https://medium.com/@ianhlake/you-are-correct-the-viewmodel-is-destroyed-if-your-process-is-killed-by-android-ef611fcd51e6

You are correct: the ViewModel is destroyed if your process is killed by Android. Just like before, you should use onSaveInstanceState() to store any data you must have to later recreate your Activity in the same state as before.

我也推荐阅读 Android ViewModel 架构组件存在危险

It seems Google offers a solution for this now

ViewModel 的保存状态模块

UI State is usually stored or referenced in ViewModel objects, not activities; so using onSaveInstanceState() requires some boilerplate that this module can handle for you.

When the module is set up, ViewModel objects receive a SavedStateHandle object via its constructor. This is a key-value map that will let you write and retrieve objects to and from the saved state. These values will persist after the process is killed by the system and remain available via the same object.


设置

implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-rc02'(2019 年 11 月 7 日)


用法

In order to set up a ViewModel to receive a SavedStateHandle you need to create them using a Factory that extends AbstractSavedStateVMFactory.

SavedStateViewModel vm = new ViewModelProvider(this, new SavedStateVMFactory(this))
        .get(SavedStateViewModel.class);

After that your ViewModel can have a constructor that receives a SavedStateHandle:


public class SavedStateViewModel extends ViewModel {
    private SavedStateHandle mState;

    public SavedStateViewModel(SavedStateHandle savedStateHandle) {
        mState = savedStateHandle;
    }
    ...
}

存储和检索值

The SavedStateHandle class has the methods you expect for a key-value map:

  • get(String key)
  • contains(String key)
  • remove(String key)
  • set(String key, T value)
  • keys()