Android 架构组件:ViewModel 不断重新初始化

Android Architecture Components: ViewModel keeps getting re-initialised

我有一个使用 ViewModel 架构组件的 activity:

class RandomIdViewModel : ViewModel() {
    var currentId : MutableLiveData<String?> = MutableLiveData()

    init {
        currentId.value = UUID.randomUUID().toString()
    }
}

然后在我的 Activity 中,我在 onCreate() 方法中有这个:

viewModel = ViewModelProviders.of(this).get(RandomIdViewModel::class.java)
viewModel.currentId.observe(this, idObserver)

每次我旋转 phone 时,Id 都会改变。所以我很困惑为什么在设置 viewModel 对象时调用 init。

编辑

我一直在查看 saving state UI guidelines,看来 ViewModel 应该在整个简单的配置更改过程中维护它的数据:

ViewModel is ideal for storing and managing UI-related data while the user is actively using the application. It allows quick access to UI data and helps you avoid refetching data from network or disk across rotation, window resizing, and other commonly occurring configuration changes. ...

ViewModel is ideal for storing and managing UI-related data while the user is actively using the application. It allows quick access to UI data and helps you avoid refetching data from network or disk across rotation, window resizing, and other commonly occurring configuration changes

似乎 activity 中有一个全局变量存储了对 ViewModel 的引用作为一次性的导致了这个问题。所有示例似乎都在局部变量中使用 VM,这对我不起作用(我不希望我的观察者被声明为内联,因为它开始使代码变得非常混乱1).每次发生配置更改时,局部变量似乎都会获得一个新实例。但是,如果我创建一个方法:

private fun viewModel() = ViewModelProviders.of(this).get(RandomIdViewModel::class.java)

每当我需要 VM 时,我都会调用它。我认为这是一个很可能在未来得到解决的错误。

1 作为旁注,我还需要指出,当 activity 不使用它们时,我还必须删除我的观察者。这也是为什么我不能直接内联观察者的定义,因为它们发生在不同的生命周期事件中:

override fun onResume() {
    super.onResume()
    viewModel().currentId.observe(this, idObserver)
}

override fun onPause() {
    viewModel().currentId.removeObserver(idObserver)
    super.onPause()
}