2

Issue:

While working with Navigation Library, I observed when I navigate back to the previous fragment, it recreates the fragment and thus re-registering all my Observers which triggers OnChanged() again

I have a Snackbar which shows some error messages example if I am looking for no more data present or no Internet connection to the server:

deliveriesListViewModel.isMoreDataPresent.observe(this, Observer {
        if (!it) showSnackBar(getString(R.string.no_more_data))
    })

Source of above code here

And on navigating back and forth, the SnackBar pops up every time, and also every time I change the orientation or rotate my device.

My architecture has a single Activity with startDestination as my ListFragment in the navigation graph and a DetailFragment as destination. SupportNavigationUp or a simple OnBackPressed on DetailFragment returns me to my ListFragment and then recreates the fragment and thus re-registering all my Observers which triggers OnChanged() again and the SnackBar pops up when noMoreDataPresent LiveData is false

Now I tried the solution from here but unfortunately, it doesn't work

I have also tried to switch my LifecycleOwner to my activity by that also doesn't work. Tried moving the ViewModelProviders.of to OnCreate and onActivityCreated - doesn't work

Please suggest corrections or any ideas what can be done to prevent SnackBar popping up after navigation and orientation change.

Footnotes

I have gone through these issues:

here is my complete source code

James Z
  • 12,209
  • 10
  • 24
  • 44
shadygoneinsane
  • 2,226
  • 1
  • 24
  • 47

1 Answers1

0

This article, especially item 1, might be relevant to what you're experiencing. Basically, what happens is that you may have multiple spawned Observers every time you navigate back to your fragment, thus executing onChanged multiple times. Using the fragment's view lifecycle as the LifecycleOwner should prevent this from happening, so your code above would look like this:

deliveriesListViewModel.isMoreDataPresent.observe(viewLifecycleOwner, Observer {
        if (!it) showSnackBar(getString(R.string.no_more_data))
    })
Alvin Dizon
  • 1,855
  • 14
  • 34