How to avoid "navigation XYZ cannot be found from the current destination"

Viewed 189

Some crashes have popped out on my Firebase's crashlytics with the exception

Fatal Exception: java.lang.IllegalArgumentException Navigation ACTION_XYZ cannot be found from the current destination

I've debugged this case and found out the problem: I have a button which navigates from Fragment A to Fragment B and it works good. But when you quickly click the button two times - first it navigates correctly, then tries to navigate again, thus the exception.

How should one avoid such a bug? I could just silently catch the exception from the button's click but that looks like a code smell to me. I also could disable the button after the first click, but I'm wondering if there is a more elegant and cleaner way to avoid double navigation to FragmentB?

Thanks for all the answers, cheers!

1 Answers

Before navigating to any screen, you can check whether we have action to that particular destination from the current screen. Something like below. You can use this extension function to navigate safely to any destination.

fun NavController.navigateSafe(directions: NavDirections, navOptions: NavOptions? = null) {
    currentDestination?.getAction(directions.actionId)?.let {
        navigate(directions, navOptions)
    }
}
Related