Roberto Leinardi
Roberto Leinardi

Reputation: 14439

Compose navigation: How to avoid to add the current destination to the back queue once you navigate out of it?

The use case is the following:

  1. I have a back queue with already several destinations.
? -> ... -> ?
  1. A new destination, let's call it Foo screen, is shown and is currently at the top.
? -> ... -> ? -> F
  1. From the Foo screen I want to navigate to a new Bar screen but, depending on a certain condition, when navigating back I want to either go back to the Foo screen or skip the Foo screen and go directly to the previous screen in the queue.
if (skipFoo)
   ? -> ... -> ? -> B
else
   ? -> ... -> ? -> F -> B

Can this be achieved using the NavOptionsBuilder from androidx.navigation?

I know that I can use popUpTo(0) { inclusive = true } to remove everything but the new destination from the stack but I just want to prevent the current screen to be added when I'm navigating out of it, and only when a certain condition is satisfied.

Also, the content of the stack of destinations is dynamic (the Foo screen can be added at any time) so I can't simply hardcode a popUpToId with a fixed destination, since I don't know what is the destination immediately before Foo screen on the stack.

Upvotes: 4

Views: 3712

Answers (2)

Chirag Thummar
Chirag Thummar

Reputation: 3242

It can be achieved by following the code. it has helped me.

Example 1:

Pop everything up to the "home" destination off the back stack before navigating to the "friendslist" destination

navController.navigate("friendslist") {
    popUpTo("home")
}

Example 2:

Pop everything up to and including the "home" destination off the back stack before navigating to the "friendslist" destination

navController.navigate("friendslist") {
    popUpTo("home") { inclusive = true }
}

Example 3:

Navigate to the "search” destination only if we’re not already on the "search" destination, avoiding multiple copies on the top of the back stack

navController.navigate("search") {
    launchSingleTop = true
}

Ref Taken: https://developer.android.com/jetpack/compose/navigation

Upvotes: 2

Roberto Leinardi
Roberto Leinardi

Reputation: 14439

It can be done using popUpTo:

navController.navigate(Screens.Bar.route) {
    popUpTo(Screens.Foo.route) {
        inclusive = true
    }
}

Upvotes: 4

Related Questions