6

I am trying to add a Listener and receive a callback whenever the navigation transition has finished in Jetpack Compose.

I have tried to use the NavController API addOnDestinationChangedListener but it is send immediately to my listener and is not waiting for the composition to finish.


val navController = rememberNavController()

// Register the destination changed listener
navController.addOnDestinationChangedListener { _, destination, _ ->
    // destination change is sent immediately and isnt waiting for the composable to finish
}

My goal is to add a listener that is only fired once the composition is completed and the destination is changed.

something like this:

// Register the transition finished listener
navController.transitionFinished{ _, destination ->
    // Do something when the navigation transition has finished
}

    NavHost(navController = navController, startDestination = "Home") {
        composable("Home") { 
            Text("FIRST SITE")
            //FIRE NOW THE CALLBACK AFTER IT FINISHED COMPOSITION
        }
        composable("Settings") {
            Text("SECOND SITE")
            //FIRE NOW THE CALLBACK AFTER IT FINISHED COMPOSITION
        }
    }

Where it will only fire callback once the whole composable is finished its composition.

Are there options to get the current tranistioning state of the navHost so I can implement it myself or any other API calls I can use?

EDIT1: TO Clarify: I define finishing composition as the whole transition animation is finished

Ojav
  • 678
  • 6
  • 22

1 Answers1

6

I'm a bit confused by your code because it seems you are mixing classic AndroidX Navigation (findNavController()) and Navigation Compose here.

Here's a full Compose example of what you want to achieve:

val navController = rememberNavController()
val currentBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute by remember { derivedStateOf { currentBackStackEntry?.destination?.route ?: "Home" } }

NavHost(
  navController = navController,
  startDestination = "Home",
) {
  ...
}

The value of currentRoute contains the current route of the NavController and since it's a State it automatically updates when the destination changes.

Sven Jacobs
  • 6,278
  • 5
  • 33
  • 39