屏幕旋转后,Android Arch组件ViewModel和LiveData触发 [英] Android Arch Components ViewModel and LiveData trigger after screen rotation

查看:245
本文介绍了屏幕旋转后,Android Arch组件ViewModel和LiveData触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用ViewModelLiveData时遇到问题我是使用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.

我的情况很简单:

  1. 使用电子邮件和密码登录屏幕
  2. 用户单击登录"按钮
  3. viewmodel调用login(email, password)并设置LiveData对象的值
  4. 现在简单地展示一个吐司面包
  1. Login screen with email and password
  2. User clicks on the "login" button
  3. the viewmodel calls the login(email, password) and set the value of the LiveData object
  4. 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:

JoseAlcérreca的处理此问题的帖子

JoseAlcérreca的EventObserver

基本上:

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆