简体   繁体   中英

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?

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.

The correct way to do this I don't think was available at the time but you should scope your view models to your navigation graphs, this way the data is cleared by the system and you only handle the navigation, quick example:

private ViewModelStoreOwner getStoreOwner() {
        NavController navController = Navigation
                .findNavController(requireActivity(), R.id.root_navigator_fragment);
        return navController.getViewModelStoreOwner(R.id.root_navigator);        
}


private void setUpSearchViewModel() {
    searchViewModel = new ViewModelProvider(getStoreOwner()).get(SearchViewModel.class);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM