Search code examples
android-adapterandroidxandroid-architecture-componentsandroid-architecture-navigation

Is it safe to use Navigation component in an Adapter?


I'm using a recycler view to display a feed, and each item is a button defined in the xml view. I'm just curious if its safe to use the navigation component and navigate when clicking an item in the recycler view, from the adapter. I currently have an onClickListener setup for the button inside of onBindViewHolder, where in the onClick I set the following:

TabsFragmentDirections.ActionNavHomeToNavGroupsFeed action =
                        TabsFragmentDirections.actionNavHomeToNavGroupsFeed(
                                myListData.getGroupName()
                        );
Navigation.findNavController(view).navigate(action);

where the Directions class is generated from using safe-args to pass an argument to the destination (from here https://developer.android.com/guide/navigation/navigation-pass-data).

Thank you!!


Solution

  • Yes I would say this is safe. Your adapter lives as long as your fragment/activity so it doesn't seem like there would be any chance of a leak.


    Having said that, it is generally considered better practice to implement that type of logic outside of the adapter for better separation of concerns!