Home > Software engineering >  Compose navigation is configuration change?
Compose navigation is configuration change?

Time:10-29

I have a remembered mutable state of type String (message) in one composable (MainView). If I modify the string and navigate to another composable (NextView), upon popping back, the modification is not remembered. If I use rememberSaveable instead, the modification is remembered. Is this the expected behavior of remember {}? If so, is navigation to another composable and back considered a configuration change?

I'm using Android 12 (API Level 31), Kotlin 1.5.31, compose version 1.1.0-alpha06, navigation-compose 2.4.0-alpha10, lifecycle-runtime-ktx 2.4.0-rc01, activity-compose 1.4.0-rc01.

Here's my code:

@Composable
fun MainView(navController: NavController) {
    var message by remember { mutableStateOf("Message") }
    // modification remembered if rememberSaveable used instead

    Column {
        TextField(
            value = message,
            onValueChange = { message = it }
        )
        Button(onClick = { navController.navigate("NextView") }) {
            Text(text = "MainView")
        }
    }
}

@Composable
fun NextView(navController: NavController) {
    Button(onClick = { navController.popBackStack() }) {
        Text(text = "NextView")
    }
}

(I'd be happy to share my other dependency and system info and the MainActivity where I set up NavHost with these two views if helpful.)

CodePudding user response:

Navigation is not considered a configuration change. Changes to your device such as its orientation, changing the default system language, wifi switching on/off are configuration changes. In most cases, a configuration change will result in your activity being destroyed. If your activity gets destroyed, anything that uses just remember gets lost. But if you use rememberSaveable, the state will be restored when the activity gets restarted.

  • Related