My navigation graph has an auth sub-graph containing a LoginFragment and a SignUpFragment:
<navigation
android:id="@+id/auth"
app:startDestination="@id/loginFragment">
<fragment
android:id="@+id/signUpFragment"
[...]
<fragment
android:id="@+id/loginFragment"
[...]
</fragment>
[...]
</navigation>
I want to check if either of those 2 destinations is currently on the backstack. But instead of checking for each destination separately, like this:
val currentDestId = navController.currentDestination?.id
if (currentDestId != R.id.loginFragment && currentDestId != R.id.signUpFragment) {
navController.navigate(
NavGraphDirections.actionGlobalLogin()
)
}
I think it would be cleaner to just check if the auth graph is currently on the back stack.
My current approach is the following:
val authBackStack = try {
navController.getBackStackEntry(R.id.auth)
} catch (t: Throwable) {
null
}
if (authBackStack == null) {
navController.navigate(
NavGraphDirections.actionGlobalLogin()
)
}
The idea here is that getBackStackEntry throws an IllegalStateException if the passed destination (or graph in this case) is not currently on the back stack. We use this exception as an indicator to find out if our graph is currently on the back stack or not.
Is this a valid approach or will it break in certain scenarios? Or maybe is there even a better approach to check if the back stack contains destinations of a certain sub-graph?