Compose Navigation how to check current navigation's route and match it with data class/object?

@Serializable
data object HomeRoute
composable<HomeRoute> { entry ->
HomeRoute(...)
}
val currentBackStackEntry = navController.currentBackStackEntryAsState()
val route = currentBackStackEntry.value?.destination?.route
LaunchedEffect(route) {
val homeClassName = HomeRoute::class.java.name
Timber.d("currentRoute: $route vs $homeClassName, ${route?.startsWith(homeClassName)}")
}
In the debug it prints:
currentRoute: com.example.app.home.navigation.HomeRoute vs com.example.app.home.navigation.HomeRoute, true
But for release build with isMinifyEnabled = true
it won't work because HomeRoute
will be obfuscated but navigation routes won't be:
It prints:
currentRoute: com.example.app.home.navigation.HomeRoute vs P5.d, false
In this case I would need to add @Keep
annotation:
@Keep
@Serializable
data object HomeRoute
Is there any other way to match/compare routes?
Answer
There is actually NavDestination.hasRoute
extension:
@OptIn(InternalSerializationApi::class)
@JvmStatic
public fun <T : Any> NavDestination.hasRoute(route: KClass<T>) =
route.serializer().generateHashCode() == id
val currentBackStackEntry = navController.currentBackStackEntryAsState()
val isHomeRoute = currentBackStackEntry.value?.destination?.hasRoute(HomeRoute::class)
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles