Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log navigation back stack in Jetpack Compose?

An example, the app first starts with screen A in the back stack, then navigates to screen B, then navigates again to screen C, and finally popUpTo Inclusive back to class A.

|--------|     |--------|     |--------|      |--------|
|    A   |  => |    B   | =>  |    C   |  =>  |    A   |
|--------|     |--------|     |--------|      |--------|
               |    A   |     |    B   |
               |--------|     |--------|
                              |    A   |
                              |--------|

How can I log what is inside the back stack for every change after a certain action like pop and navigate was done, that happens in my application?

like image 814
Denny Kurniawan Avatar asked Feb 26 '26 01:02

Denny Kurniawan


2 Answers

Use currentBackStack.value instead backQueue

navController.addOnDestinationChangedListener { controller, _, _ ->
    val routes = controller
        .currentBackStack.value
        .map { it.destination.route }
        .joinToString(", ")

    Log.d("BackStackLog", "BackStack: $routes")
}
like image 62
alvaro_se Avatar answered Feb 27 '26 15:02

alvaro_se


This can be used straight in composable:

/**
 * Logs Navigation backstack
 * output example:
 * ```
 * NavigationBackStack:
 * com.example.Route.Root
 * com.example.Route.Home
 *
 * ```
 */
@SuppressLint("RestrictedApi")
@Composable
fun LogNavigationBackStack(navController: NavController) {
    if (BuildConfig.DEBUG) {
        LaunchedEffect(Unit) {
            navController.currentBackStack
                .collect { entries ->
                    entries.map { it.destination.route }
                        .joinToString("\n")
                        .let {
                            Log.d("Navigation", "NavigationBackStack: \n$it" )
                        }
                }
        }
    }
}
like image 23
Vouskopes Avatar answered Feb 27 '26 14:02

Vouskopes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!