I have a chip that changes configurations when being clicked on. However, as the user navigates back (popbackstack) or navigates to another screen, the clicked chip re-sets its previous position. As I understood, I will have to use a viewmodel to pass the chips state and in that way save it? I cant find a way though to store the "remembersavable" in a viewmodel.
How can I achieve this? Appreciate any feedback!
My example chip:
@Composable
fun CatsChip() {
val textChipRememberOneState = rememberSaveable { mutableStateOf(false) }
TextChip(
isSelected = textChipRememberOneState.value,
shape = Shapes(medium = RoundedCornerShape(15.dp)),
text = "Cats",
selectedColor = LightGreen,
onChecked = {
textChipRememberOneState.value = it
},
)
}
You can keep the state in a
MutableStateFlowin aViewModel.To use
ViewModels in Compose you need to add the following dependency to yourapp/build.gradlefileNow you can use the
viewModel()function to get theViewModelinstance in your composables.With
ViewModels you do not need to userememberSaveableanymore, since the state will be kept in theViewModel, however, if you want the state to persist even across process death (not just configuration changes), then you have to save the state in theSavedStateHandle.Here is an example of a
ViewModelthat only keeps the state in memory, but does not save it in theSavedStateHandle.Here is an example of a
ViewModelthat saves the state in theSavedStateHandle.Then the usage would look like this
For more use cases see also the Business Logic section of the Compose State Hoisting documentation
Here is a demo
Composableusing Compose navigation and showcasing the two view models from above, comparing it withrememberSaveable, scoping them in two different ways, to the parent context and to theNavBackStackEntry. This shows how different scopes affect the lifecycle ofViewModels.Requires the Compose navigation dependency in your
app/build.gradlefileYou can check the demo by calling
Demo()in some composable content of your app. Click the buttons to navigate and see how the backstack changes. TheViewModels and also therememberSaveablethat are scoped to the parent context will preserve the state all the time, whereas those that are scoped to eachNavBackStackEntrywill preserve state only for their own navigation destinations, which can be seen when navigating back. Also the state saved in theMemoryOnlyViewModels will not survive process death, which you can check in the following way:If you followed the steps correctly and managed to kill and restore the process in this way, then you should notice that only
MemoryOnlyViewModels have lost/reset their state.Here is the whole demo code. Just copy and paste to a new Kotlin file and call the Demo() composable from a composable content.