安卓架构组件 : ViewModel keeps getting re-initialised

标签 android mvvm android-viewmodel

我有一个使用 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)

每次我旋转手机时,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()
}

关于安卓架构组件 : ViewModel keeps getting re-initialised,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50696495/

相关文章:

design-patterns - 在 MVVM 模式中,模型和 View 什么时候直接相互通信?

qt - 在 QtQuick 中应用 MVVM 模式

android - Dagger-Hilt:@ViewModelInject 没有注入(inject) MyViewModel 并崩溃?

android - 如何以编程方式锁定/解锁手机 : Android

java - VM初始化时出错java/lang/NoClassDefFoundError : java/lang/ref/FinalReference

android - 上下文操作模式 AppCompatActivity 不显示

c# - CinchV2 中的模型发生了什么?

android - 具有 Intent 操作的 onStartCommand 与绑定(bind)服务

android - 由 : java. lang.RuntimeException : Cannot create an instance of class com. app.MyViewModel 引起

Android:通过Activity中的LiveData和ViewModel观察Room DB