https://kotlinlang.org logo
#compose
Title
# compose
t

Tgo1014

06/17/2022, 11:47 PM
Using compose navigation, how can I make sure one destination has only one instance? I'm handling a intent from the main screen to a detail screen, but if the user click many times the intent then when pressing back it goes to the previous detail screen instead of the main screen
f

Francesc

06/17/2022, 11:51 PM
you can query the current destination before you try to navigate, if you are no longer where you expect to be then ignore the button click
t

Tgo1014

06/17/2022, 11:53 PM
I found this, settings where it should pop up to works I guess: https://stackoverflow.com/a/71412193/6022725
f

Francesc

06/17/2022, 11:54 PM
when you handle the button click, you can check this
Copy code
if (navController.currentBackStackEntry?.destination != <nav id of where the button is>) {
   // navigate
}
t

Tgo1014

06/17/2022, 11:56 PM
Let me try
f

Francesc

06/17/2022, 11:56 PM
you probably want to get the
route
or the
id
from the backstack entry to compare, I'm just typing this from memory
t

Tgo1014

06/17/2022, 11:56 PM
Hmm but in my case it doesn't work because I still need to navigate, the thing is when going back
My issue is like A -> B -> B -> B
so when I go back instead of always A -> B
f

Francesc

06/17/2022, 11:57 PM
do you want to debounce clicks on the back button to navigate back?
t

Tgo1014

06/17/2022, 11:58 PM
No, I want to go back to the first one, skipping all the B instances
f

Francesc

06/17/2022, 11:58 PM
then you can use popUpTo(A, inclusive = false)
t

Tgo1014

06/17/2022, 11:59 PM
Using this solved for now, just not sure it's the best way
Copy code
navController.navigate(B) {
    popUpTo(A) {
         inclusive = false
    }
}
f

Francesc

06/17/2022, 11:59 PM
not
popUpTo
but
popBackStack
but that's the idea
t

Tgo1014

06/18/2022, 12:04 AM
I tried
popBackStack
but for wear when you swipe back it goes back to another B, if I set it as
popUpTo
then it works 👀
i

Ian Lake

06/18/2022, 12:11 AM
This is exactly what
launchSingleTop
is for. Have you tried using that?
to only have a single instance of a destination on the top of the stack
t

Tgo1014

06/18/2022, 12:12 AM
Isn't this a Manifest thing? I've just one activity where all destinations are composable screens
i

Ian Lake

06/18/2022, 12:12 AM
Copy code
navController.navigate(B) {
  launchSingleTop = true
}
t

Tgo1014

06/18/2022, 12:13 AM
Oh, I didn't know you could use it like this, seems like this would solve the problem 😄
i

Ian Lake

06/18/2022, 12:13 AM
t

Tgo1014

06/18/2022, 12:14 AM
Yeah, my google search failed me 😄 Thanks for the help Ian!
👍 1
51 Views