0

I'm having a peculiar issue. In my code, I observe a MutableLiveData of type String in view Model and display the context as a toast. When I run it in the AVD, the toast is being displayed more than once i.e the MutableLiveData is being observed more than once. But, when I run the same code in my Mobile, toast is displayed only once (works as expected).

Code (Fragment):

if(!viewModel.messageDisplayed) {
                viewModel.MessageStatus.observe(viewLifecycleOwner, Observer {
                    it.toast(context)
                    viewModel.messageDisplayed = true // I'm using this variable to avoid displaying the toast multiple 
                                                     //times but it does not work in the emulator 
                })
            }

Code (ViewModel):

val MessageStatus = MutableLiveData<String>()

fun fireStoreOperations(){
    //fireStore Operations
        .addOnSuccessListener{
         messageDisplayed= False
         MessageStatus.value = "Message to be displayed"
        }
}
Anirudh Ganesh
  • 446
  • 4
  • 22

2 Answers2

0

You can put the observer in the onActivityCreated of your fragment. So it would look something like

@Override
public void onActivityCreated(Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);
    viewModel.MessageStatus.observe(viewLifecycleOwner, Observer {
                it.toast(context)
                viewModel.messageDisplayed = true 
            })
}
tony
  • 466
  • 6
  • 22
0

You have to check that you are calling this method once. if your observer for a LiveData<*> should not be called multiple times. for more details this can help