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

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

问题描述

我在使用 ViewModelLiveData 架构组件时遇到问题.当使用 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.

我的场景相对简单:

  1. 使用电子邮件和密码登录屏幕
  2. 用户点击登录"按钮
  3. viewmodel调用login(email, password)并设置LiveData对象的值
  4. 现在只是简单地展示一个 Toast
  1. Login screen with email and password
  2. User clicks on the "login" button
  3. The viewmodel calls the login(email, password) and sets the value of the LiveData object
  4. 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处理这个问题的帖子

Jose Alcérreca 的事件观察员

Jose Alcérreca 的 SingleLiveEvent 类

基本上:

在视图模型中:

var eventLiveData: MutableLiveData>= MutableLiveData()

在活动或片段中:

viewModel.eventLiveData.observe(this, EventObserver {
     it?.let {
          shortToast(it.message)
     }
})

这篇关于Android Arch 组件 ViewModel 和 LiveData 在屏幕旋转后触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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