We’ll discuss how to setup Compose Navigation by using Google’s navigation library.
Kindly check the part 1 of this series: https://sanjaydev.tech/blog/step-by-step-guide-to-setup-androidx-compose-navigation-part-1-6d4c724db0bb
This will be the part 2 of "AndroidX Compose Navigation" Series.
In the last part, we have developed a simple navigation, here comes the preview.
Let's add some spicy states... For simplicity I'll add a count state.
@Composable
fun FirstScreen(navigateToSecondScreen: () -> Unit) {
OuterComposable {
// Newly added count state
var count by remember {
mutableIntStateOf(0)
}
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "First Screen", fontSize = 48.sp)
// Added a new button to change state
Button(onClick = { count++ }) {
Text(text = "Count: $count")
}
Button(onClick = {
navigateToSecondScreen()
}) {
Text(text = "Navigate to 2nd Screen")
}
}
}
}
Let's run the code in our Intent Navigation.
It works as expected, lets do the same for our Compose Navigation.
It may look working, But look closely for the count state, it resets when coming back from Second Screen. Why?
We have declared the count state inside the First Screen, while navigation FirstScreen is getting destroyed and recreated while coming back.
Three options to fix this:
Add the count state out of the First Screen, into the MainActivity class itself.
Add a ViewModel, add these state inside the Viewmodel.
Instead of
remember
userememberSaveable
.
I tried three options, but third option seems to have less code changes 😜.
Adding ViewModel may be a overkill.
remember
and rememberSaveable
are same, but differs in one feature.
It attaches the state to Parent Activity.
Note: Don't use rememberSaveable
more often, as it has a size limit.
Let's change remember
with rememberSaveable
.
Now it works as same as our Intent Navigation, No loss of state.
Source Code
Repository: https://github.com/SanjayDevTech/compose-navigation-tutorial.
I have added the Screens in a separate
screens
module.app
module has the Compose Navigationoldapp
module has the Intent Navigation
That's it for the Part 2.