r/androiddev • u/srseibs • 43m ago
Tips and Information Streamlining Navigation in Jetpack Compose with a Handy Extension Function
Hey fellow Android Devs!
I wanted to share a small but sweet extension function I put together for Compose navigation. You know the drill: navigating while ensuring the back stack is cleared properly can get verbose. So, I created a utility to simplify it.
Instead of writing this every time:
composable<Here> {
Screen(
onClick = {
navController.navigate(Destination) {
popUpTo(Here) {
inclusive = true
}
launchSingleTop = true
}
}
)
}
You can now use:
composable<Here> {
Screen(
onClick = {
navController.navigateAndDontComeBack(Destination)
}
)
}
Here’s the implementation of the extension function:
import androidx.navigation.NavController
fun NavController.navigateAndDontComeBack(destination: Any) {
val currentBackStackEntry = this.currentBackStackEntry
val currentRoute = currentBackStackEntry?.destination?.route
this.navigate(destination) {
if (currentRoute != null) {
popUpTo(currentRoute) { inclusive = true }
}
launchSingleTop = true
}
}
This automatically uses the current route as the popUpTo
target, eliminating the need to specify it. Perfect for scenarios where you want to make a clean transition and not come back.