2022/06/04
When working on an Android application, it’s common to have a scenario where you want to avoid navigating to the same route multiple times on button presses. For example, let’s say we have a button on the home screen that takes you to a profile page. If the user taps the button repeatedly, we don’t want to navigate to the profile page multiple times.
One way to solve this is by comparing the route we want to navigate to with the route found in the currentDestination.route field of the NavController. If the routes are the same, it means we are currently navigating to the requested route, and we don’t need to call the navigate method again.
This is how the solution would be implemented in a Jetpack Compose button:
_13@Composable_13fun NavigationExample(_13 navController: NavController = rememberNavController()_13) {_13 Button(onClick = {_13 val targetRoute = "YOUR_ROUTE"_13 if (navController.currentDestination?.route !== targetRoute) {_13 navController.navigate(targetRoute)_13 }_13 }) {_13 Text(text = "Navigate")_13 }_13}
By implementing an extension method for the NavController, we can avoid repeating the same code in other places if we want to implement the same functionality:
_17@Composable_17fun NavigationExample(_17 navController: NavController = rememberNavController()_17) {_17 Button(onClick = {_17 val targetRoute = "YOUR_ROUTE"_17 navController.navigateOnce(targetRoute)_17 }) {_17 Text(text = "Navigate")_17 }_17}_17_17private fun NavController.navigateOnce(targetRoute: String) {_17 if (this.currentDestination?.route !== targetRoute) {_17 this.navigate(targetRoute)_17 }_17}
In conclusion, by comparing the route we want to navigate to with the currentDestination.route
field of the NavController
, we can avoid navigating to the same route multiple times on button presses. By implementing an extension method for the NavController
, we can easily reuse this functionality in other places.