One Off the Slack: Do We Need State To Remember?

Cafer Mert Ceyhan asked:

According to the rememberSaveable’s documentation, it says: “If you use it with types which can be stored inside the Bundle then it will be saved and restored automatically using autoSaver, …“. So, I was expecting this code can survive during the configuration changes but it doesn’t. Am I missing something?

var foo = rememberSaveable { false }

Csaba Szugyiczki wondered:

how do you change the value of foo?

I think you need to us it like this, otherwise you will change the value of the variable foo, and not the value backed in the rememberSaveable

var foo by rememberSaveable { mutableStateOf(false) }

Cafer then elaborated:

Yes if I wrap it with mutableStateOf() it works but I don’t need the State because of I don’t need recomposition. I want to save this variable during the configuration changes.

var foo = rememberSaveable { false }

LaunchedEffect(Unit) {
    if (!foo) {
        foo = true

Csaba then explained more about the problem:

you are saving false and reading false all the time. Inside the LaunchedEffect what happens is the foo variable gets the value of true, but that does not change the originally saved value which is false

Maybe you can create a reference object that you can modify without triggering a recomposition, and save the value stored in that like in this article:

But I cant see why you would need anything like this. This side effect seems to be way more complicated than it should usually be

Cafer agreed:

I see the problem, saying foo = true doesn’t change the saved value, right? It makes sense, looks like I should use mutableStateOf() even if I don’t need it. It is easy solution.

Google’s Ian Lake then chimed in to help clarify what is really going on here:

mutableStateOf() creates a MutableState object - a recomposition aware wrapper around a set and get. While you may not need the recomposition aware part, what rememberSaveable is capturing is that wrapper object - that’s why when the autoSaver calls get, it gets the latest value you’ve set

Any wrapper would do, it just happens to be that you get a prebuilt one for you in Compose land 🙂

And, when Cafer asked if Ian recommended mutableStateOf() even if recompositions are not needed, Ian said:

Just use mutableStateOf(), then if your requirements change and you do need the recomposition part, you’ll get that for free

Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!