According to the rememberSaveable’s <documentation...
# compose
m
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 }
c
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) }
m
Foo is always false in the LaunchedEffect. 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.
Copy code
var foo = rememberSaveable { false }

LaunchedEffect(Unit) {
    if (!foo) {
        foo = true
    }
}
c
yeah, but the problem is, 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
👆 4
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 https://www.jetpackcompose.app/articles/how-can-I-debug-recompositions-in-jetpack-compose#printing-log-statements
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
what do you want to achieve?
☝️ 1
m
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.
i
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 🙂
m
Thank @Ian Lake! Do you suggest using
mutableStateOf()
even if I don’t need it or suggest creating a holder for this?
i
Just use
mutableStateOf()
, then if your requirements change and you do need the recomposition part, you'll get that for free
🙏 1
👍 1