Android Arch Components ViewModel and LiveData trigger after screen rotation

前端 未结 2 1217
无人及你
无人及你 2020-12-30 03:58

I have a problem when using ViewModel and LiveData I am new using ViewModel and LiveData arch components and have the problem when using frag

2条回答
  •  攒了一身酷
    2020-12-30 04:48

    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> = MutableLiveData()

    and In Activity or Fragment:

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

提交回复
热议问题