屏幕旋转后,Android Arch组件ViewModel和LiveData触发 [英] Android Arch Components ViewModel and LiveData trigger after screen rotation
问题描述
在使用ViewModel
和LiveData
时遇到问题我是使用ViewModel和LiveData拱形组件的新手,在使用fragments
并旋转观察者被触发的屏幕时出现问题...
我试图移动
I have a problem when using ViewModel
and LiveData
I am new using ViewModel and LiveData arch components and have the problem when using fragments
and rotate the screen the observer get triggered...
I tried to move the
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
在所有片段生命周期方法中都没有成功.
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
in all the fragment lifecycle methods but with no success.
我的情况很简单:
- 使用电子邮件和密码登录屏幕
- 用户单击登录"按钮
- viewmodel调用
login(email, password)
并设置LiveData对象的值 - 现在简单地展示一个吐司面包
- Login screen with email and password
- User clicks on the "login" button
- the viewmodel calls the
login(email, password)
and set the value of the LiveData object - Just for now simple show a Toast
这时一切都很好.但是当我旋转屏幕时,Toast再次出现,没有任何用户交互.
At this point everything is Ok. But when I rotate the screen the Toast appears again without any user interaction.
我必须在onDestroyView()中做些什么吗?
Do I have to do something in onDestroyView() ?
提前谢谢!
推荐答案
确定终于找到了问题以及解决方法. 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:
在ViewModel中:
In ViewModel:
var eventLiveData: MutableLiveData<Event<ErrorResponse>> = MutableLiveData()
以及活动中"或片段"中:
and In Activity or Fragment:
viewModel.eventLiveData.observe(this, EventObserver {
it?.let {
shortToast(it.message)
}
})
这篇关于屏幕旋转后,Android Arch组件ViewModel和LiveData触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!