I'm using ViewPager 2 from AndroidX with 4 instances of the same fragment. My question is pretty straight forward. When I'm navigating to some another fragment(using navigation drawer or even something else). OnStop() , OnDestroy(), OnDettach() of the fragments inside the viewpager does not gets triggered. So why is that? And If I want to remove the listeners I've started already, in one of these methods, how can I do that?
For example, I'm using GreenRobot's EventBus. And I'm registering the EvenBus inside OnStart:
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
And Removing it from OnStop:
override fun onStop() {
Log.e(TAG, "onStop: ")
EventBus.getDefault().unregister(this)
super.onStop()
}
But when I navigate away from the viewpager as I explained above, onStop does not trigger. I even checked it by logging.
So is the fragment lifecycle works differently with viewpager? And if yes, how can I overcome this problem(unregistering EvetBus).
Unfortunately, EventBus does not provide great usefulness when it comes to ViewPager and Fragments inside it.
Though I found a solution, using the more traditional approach: Interfaces
It does not directly answer the question Why onStop is not called of fragments inside ViewPager on navigation change?
But it does save you from multiple Event triggers when using EvenBus with ViewPager. With interfaces, As you don't have to explicitly unregister the interface. It does not matter if the onStop is called.