DEV Community

Aniket Kadam
Aniket Kadam

Posted on

Navigation Component Essentials

Don't go back to loading from your list!

When you want to allow a navigation from one fragment to another, but want to prevent backwards navigation along that path, popUpTo the navpath on that action.

Useful when you're leaving a loading state, or an error state for the next screen.

Note: nav_paths is the xml file containing the navigation graph for my project.

                app:popUpTo="@id/nav_paths" />

Don't crash on a rotation!

If you use a setup where rotating the screen would result in a call to a navigate function, it's very likely you'll attempt to navigate to the same screen that you were already on.

This crashes the app with a

java.lang.IllegalArgumentException: navigation destination com.aniketkadam.someapp:id/action_loadingFragment_to_someListFragment is unknown to this NavController

To avoid that, you can use this extension function and always navigate via that. It helps if you're using NavDirections instead of typed paths to make really sure this can be a valid path at all.

All we're doing here, is making sure each node the journey to the path, is valid since nearly any of them can be null.

private fun NavController.safeNavigate(d: NavDirections) =
    currentDestination?.getAction(d.actionId)?.let { navigate(d) }
        ?: Timber.e("Invalid route for direction ${d} with id ${d.actionId}")

You can see this in use in my project here:

I didn't need it anywhere except that screen so I went with a private extension function. If you're going to use it in multiple places, please keep it with the rest of your extension functions!
Here's a good article about how to organize them.

Want to help your team get out of tricky situations? I'm available for hire as an Android Consultant. Contact me at aniket@[firstname][lastname].com

Top comments (0)