Android Arch 组件 ViewModel 和 LiveData 在屏幕旋转后触发 [英] Android Arch Components ViewModel and LiveData trigger after screen rotation
问题描述
我在使用 ViewModel
和 LiveData
架构组件时遇到问题.当使用 fragments
并旋转屏幕时,观察者被触发...
I have a problem when using ViewModel
and LiveData
arch components. When using fragments
and rotating the screen, the observer gets triggered...
我试图移动 viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
在所有片段生命周期方法中,但没有成功.
I tried to move viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
in all the fragment lifecycle methods, but with no success.
我的场景相对简单:
- 使用电子邮件和密码登录屏幕
- 用户点击登录"按钮
- viewmodel调用
login(email, password)
并设置LiveData对象的值 - 现在只是简单地展示一个 Toast
- Login screen with email and password
- User clicks on the "login" button
- The viewmodel calls the
login(email, password)
and sets the value of the LiveData object - Just for now simply show a Toast
此时一切正常.但是当我旋转屏幕时,Toast 再次出现,无需任何用户交互.
At this point everything is okay. But when I rotate the screen the Toast appears again without any user interaction.
我必须在 onDestroyView()
中做些什么吗?
Do I have to do something in onDestroyView()
?
提前致谢!
推荐答案
Ok 终于找到问题以及如何解决了.LiveData 不是为单个事件设计的.出于这个原因,有几种方法可以修复或处理它,这两个链接对我很有用:
Ok Finally found the problem and how to solve. LiveData is not designed for single events. For that reason there is a couple of ways to fix it or handle it, this two links were useful for me:
Jose Alcérreca 的 SingleLiveEvent 类
基本上:
在视图模型中:
var eventLiveData: MutableLiveData
在活动或片段中:
viewModel.eventLiveData.observe(this, EventObserver {
it?.let {
shortToast(it.message)
}
})
这篇关于Android Arch 组件 ViewModel 和 LiveData 在屏幕旋转后触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!