In this demo, you’ll use the rememberSaveable function to save the Wellness Club App’s state across configuration changes.
Start Android Studio and open the 04-lesson-configuration-changes/Starter project. Build and run the project.
Now, enter the name of a new member and rotate the screen.
Whoops! The name you just entered disappears. It got lost when the composable functions were recomposed due to the screen rotation. To save the state across configuration changes like a screen rotation, you’ll use the rememberSaveable composable function.
Open the SignUpScreen.kt file containing the starter code. The SignUpScreen() composable has a variable, memberName, whose value is currently saved using the remember function. Now, you’ll replace the remember function with the rememberSaveable function:
var memberName by rememberSaveable { mutableStateOf("") }
Build and run the app. Enter the name and email of a new club member. Then, rotate the screen.
The name is saved, but the email is lost. Mmmh! You forgot to save the email using the rememberSaveable function. Now, update the memberEmail variable to save using the rememberSaveable function:
var memberEmail by rememberSaveable { mutableStateOf("") }
Build and run the project. Enter a new member’s name and email. Then, rotate the screen.
When you rotate the screen, both name and email values are preserved.
Congratulations! You’ve learned how to persist state across configuration changes in Jetpack Compose.