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))
})
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: