Skip to content Skip to sidebar Skip to footer

How To Observe The Livedata With Multiple Observe For Correct Way In Android?

I have an Activity, and it will turn to the fragment-A and then turn to the fragment-B like the following. Activity -> Fragment-A -> Fragment-B situation 1 These two fragment

Solution 1:

You are observing the LiveData correctly, it is how the Event class is designed.

When you do

viewModel.responseData.observe(this, Observer {
            it.getContentIfNotHandled()?.let {
            showSnackBar(it)
}

getContentIfNotHandled will return content only once until there is a new value set again. If FragmentA consumes this first FragmentB will not be able to consume the same value. This is the reason peekContent works since it will always return the current value even though the event has been consumed.

If there is a solid reason where you need to show this Snackbar msg in both fragments I suggest you observe on different LiveData instances for each fragment.

You could do this by returning a new LiveData<Event<String>> everytime viewModel.getResponseData() is invoked.

Post a Comment for "How To Observe The Livedata With Multiple Observe For Correct Way In Android?"