I'm trying to add a mutable list of parcelable objects to my composable. I also want to be able to add objects to and remove objects from it.
Currently I'm using something like this:
val names = remember { mutableStateListOf<String>() }
names.add("Bill")
names.remove("Bill")
Now I want this list to survive configuration change, therefore it's perhaps a good idea to use rememberSaveable
. Perhaps something like this:
val names = rememberSaveable { mutableStateListOf<String>() }
names.add("Bill")
names.remove("Bill")
But this does not work, it throws the following exception:
androidx.compose.runtime.snapshots.SnapshotStateList cannot be saved using the current SaveableStateRegistry. The default implementation only supports types which can be stored inside the Bundle. Please consider implementing a custom Saver for this class and pass it to rememberSaveable().
This means, that SnapshotStateList
(the result of mutableStateListOf
) is not saveable.
So far I can think of few ways how to work around this:
- Actually implementing a saver for
SnapshotStateList
. - Using something like
val namesState = rememberSaveable { mutableStateOf(listOf<String>()) }
. This does indeed work flawlessly, however updating the list requires setting the value, which is both slow and inconvenient (e.g.namesState.value = namesState.value + "Joe"
for just adding a single element).
Both these ways seem too complicated for a seemingly small task. I wonder what is the best way to do what I want. Thanks.