Jetpack compose navigation if current destination is last destination of stack

1.3k views Asked by At

I am using Jetpack compose with one activity & multiple composable destinations.
Activity named is MainActiviy & Composable destinations are A->B->C
Suppose I am in C & I backpress, I need to know in onBackPressed() of mainActivity that now in backstack of navigation destinations 2 destinations are left.
Can anyone please help on this

1

There are 1 answers

0
Andreas Lindquist On

Not really sure what you are looking for, but it might be useful to call addOnDestinationChangedListener in your fragment or activity.

You get notified when destinaton changes and get hold of the route and the navController. Maybe that solves your problem, IDK?

Something like this for fragment:

   @OptIn(ExperimentalAnimationApi::class)
  override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?,
  ): View {
    return ComposeView(requireContext()).apply {
      setContent {
        MyAppTheme {
          val navController = rememberAnimatedNavController()
          navController.addOnDestinationChangedListener { navController, destination, bundle ->
            if (destination.route == "A") doSomething()
            // navController.currentBackStackEntry)
          }
          AnimatedNavHost(
            navController = navController,
            startDestination = "A",
          ) {
            composable(
              route = "A",
              content = { ScreenAComposable() },
            )
            composable(
              route = "B",
              content = { ScreenBComposable() },
            )
            composable(
              route = "C",
              content = { ScreenCComposable() },
            )
          }
        }
      }
    }
  }