Search code examples
androidback-buttonandroid-jetpackandroid-viewmodelandroid-architecture-navigation

Android navigation component perform an Action when popping backstack


Im using the android navigation component and despite some early teething issues it is now working well.

I'm keeping to the one activity many fragments design principle and I'm using shared view models to communicate between fragments.

I now have a scenario in my application where the user creates something, saves it, and is returned to the main list fragment (think something like adding a new contact except it involves a lot more than just typing in some boxes)

When the user saves the information I need to clear the data from my view models (this is due to security concerns and not performance) as they are shared view models and so are tied to the activity lifecycle and not the fragment, so they won't clear themselves, I can achieve this in a normal flow just setting data to null and calling navcontroller.popBackStack() but if the user presses back themselves I have no way of knowing and thus cannot clear these view models, any ideas?


Solution

  • You can implement a listener interface (say OnBackPressedListener) and use it in your respective fragments to take action upon back button presses (or up navigation). The interface will be your bridge between your fragments and the activity.