Search code examples
androidandroid-fragmentsobserver-patternlifecycle

Binding/Unbinding EventBus in onViewCreated()/onDestroyView() with a ViewPager


I am utilizing a FragmentPagerAdapter to manage a ViewPager with 4 tabs, I'm also utilizing EventBus to monitor changes between tabs. These tabs are all related in the fact that they can add content which should update in another tab.

The way FragmentPagerAdapter works is upon a swipe to another tab, it CAN destroy the view of the previous tab (onDestroyView() seems to be called every single time the Adapter must release memory), however, it often does not destroy the view, it only pauses the fragment.

This being said, I am using an MVP design and I am currently binding the EventBus in onViewCreated() to the Presenter and then unbinding it in onDestroyView(). This allows for events from another tab to reflect instantly in preceding tabs that have been swiped away (so long as the Fragment's views exist still). This removes the necessity to use Sticky events and manage them appropriately.

If the Fragment's views are actually destroyed, when the user navigates back to the Fragment it's onViewCreated() methods will fire redrawing the entire Fragment's views from the most recent data. So both situations are covered efficiently, the situation where a view still exists (and it gets updated), as well as the situation where there is no view, and a new view must be drawn.

Therefore, I don't see any holes in my plan, however, I have NEVER seen this approach discussed. Is there a really bad reason I should not be doing this? Or is this just a good solution for a very specific design?

Your expertise is appreciated!


Solution

  • I have done similar things before. It's common practice to use an event bus along with the lifecycle of views in order to best manage their display when it's relevant to do so. The problem is registering a listener before the view is actually available, and unregistering after it's no longer going to be used, which is sounds like you are not doing.

    BTW, for anyone reading this, there are different practices for different situations. For Activity instances it is common to use onStart and onStop to register and unregister the listener, but you still have to understand the flow of events through your bus to see if it still makes sense.