compose navigation handle when composable returned after back

2.4k Views Asked by At

Let's say I have 2 screens HomeScreen and DetailScreen and use compose navigation to navigate between screens.

The graph is HomeScreen -> DetailScreen.

When I pressed back on DetailScreen and returned to HomeScreen I want HomeScreen reacted to that and had to call some method. I want HomeScreen composable to call some method every time he shows up on the screen. How to achieve that?

NavHost(
        navController = navController,
        startDestination = "Home"
    ) {
        composable("Home") {
            HomeScreen(
                onDetailClick= {
                    navController.navigate("Detail")
                }
            )
        }
        composable("Detail") {
            DetailScreen(
                onBackClick= {
                    navController.popBackStack()
                },
            )
        }
}
3

There are 3 best solutions below

0
On BEST ANSWER

You should use NavHostController.navigateUp() instead of NavHostController.popBackStack(), then you can use LaunchedEffect with a fixed value like Unit for the key.

@Composable
HomeScreen() {
    LaunchedEffect(key1 = Unit) {
        Log.i("HomeScreen", "home screen visible")

        // call your methods here
    }
    
    // the rest of HomeScreen code
}

But be careful because everytime configuration change occured it will also be re-executed.

1
On

It depends how are you back to the home screen. If you use navController.navigete("home") then it will work fine.

@Composable
HomeScreen() {
    LaunchedEffect(key1 = true) {
        Log.i("HomeScreen", "home screen visible")

        // call your methods here
    }
    
    // the rest of HomeScreen code  
}

Or, if you are using navController.popBackStack(), then it will not work.

For that, you need to first navigate to Home by using navController.popBackStack() then use navController.navigate("home")

example - >

navController.popBackStack()
navController.navigete("home")
0
On

you can use viewmodel init block to call the method which you want to execute every time when home screen is loaded. Just make sure that your viewmodel is scoped to the HomeScreen composable.

init { // call to your method }