2

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()
                },
            )
        }
}
galihif
  • 310
  • 1
  • 8

2 Answers2

2

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.

uragiristereo
  • 546
  • 1
  • 6
  • 9
0

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")
JM Lord
  • 1,031
  • 1
  • 13
  • 29
  • Navigating without specifying nav options `saveState` and `restoreState` will not restore the backstack, this is a problem since most of the time back pressing shouldn't reset the backstack. I've updated my answer to encourage to use `NavHostController.navigateUp()` instead – uragiristereo Dec 09 '22 at 03:58