Android Arch Components ViewModel and LiveData trigger after screen rotation

早过忘川 提交于 2019-11-30 04:05:12

问题


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) in all the fragment lifecycle methods but with no success.

My scenario is kind of really easy one:

  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

At this point everything is Ok. But when I rotate the screen the Toast appears again without any user interaction.

Do I have to do something in onDestroyView() ?

Thanks in advance!


回答1:


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's post dealing with this problem

Jose Alcérreca's EventObserver

Jose Alcérreca's SingleLiveEvent class

Basically:

In ViewModel:

var eventLiveData: MutableLiveData<Event<ErrorResponse>> = MutableLiveData()

and In Activity or Fragment:

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



回答2:


It's how LiveData and ViewModel works. You are getting same ViewModel with same LiveData and LiveData has previous object, User for instance, with previous credentials when you call ViewModelProviders.of(this).get(MainViewModel::class.java). You can reset User of LiveData onPause()or onStop() to reset it to initial state.

I don't know how you call toast, if you can share your ViewModel and MainActivity i can be more specific.



来源:https://stackoverflow.com/questions/51450215/android-arch-components-viewmodel-and-livedata-trigger-after-screen-rotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!