Search code examples
androidnavigationandroid-jetpack-compose

OnClick execute function multiple time


i am trying to learn jetpack compose but i have some hard time working with navigation, specifically i cant understand why this code print "notwork" two time.

@Composable
fun NavigationController() {
    var navController = rememberNavController()
    NavHost(navController, startDestination = DummyRoutes.Dummy.route) {
        composable(route = DummyRoutes.Dummy.route) {
            Dummy(
                openHome = { navController.navigate(SomeRoutes.SomeOther.route) },
            )
        }
    }
}

@Composable
fun Dummy(
    openHome: () -> Unit,
) {

    Log.d("hello", "notwork: ")
    Button(onClick = {openHome()}) {
        
    }

Solution

  • NavHost recomposing its destinations because of transition animations.

    With the initial route it only happens two times, but if you try to navigate to an other screen, there will be more recompositions of both appearing/disappearing screens. This is expected behaviour.

    If you use your own animation, your view will be recomposed up to once a frame, and this is OK too.

    There're times when you can reduce number of recompositions, e.g. when you use an often changing state, like lazy list state, check out this answer for more details.

    But with animations and navigation you can't reduce this number, and you shouldn't, because screen is actually needs to be redrawn that often. Extra recompositions won't affect your app performance if you build it right - handle side effects correctly. See more details about recompositions and side effects in Thinking in Compose.