galihif
galihif

Reputation: 444

compose navigation handle when composable returned after back

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()
                },
            )
        }
}

Upvotes: 4

Views: 3442

Answers (3)

Anand Choudhary
Anand Choudhary

Reputation: 9

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 } 

Upvotes: -1

bibeka nanda nayak
bibeka nanda nayak

Reputation: 1

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")

Upvotes: 0

uragiristereo
uragiristereo

Reputation: 874

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.

Upvotes: 2

Related Questions