I haven't seen anything in the docs about when/if ...
# compose
d
I haven't seen anything in the docs about when/if to use
remember {}
or
mutableStateOf()
inside state holders... or whether the one surrounding the object itself is enough....?
p
If associate each composible with class then: val x = remember { initialValueExpression } - like val field in class, var x by remember { mutableStateOf(initialValueExpression) } - like var field in class (changing x will also trigger recomposition if x is used below)
g
d
Thanks, I'll take a look!
Very interesting writeup! So to sum up the answer: When using properties that the compiler might take as mutable in the state holder, use
mutableStateOf
...
And if the state holder class needs to be instantiated in the Screen composable, then
remember { mutableStateOf<MyStateHolder>(MyStateHolder()) }
needs to be used there even though inside it there might be some `mutableStateOf()`s for mutable properties?
g
Yeah, pretty much
s
About when to use
remember
or not. It’s simply a matter of if you’re inside a composable function or not. If you are, you have to think that whatever you’re calling can and will potentially be called many times a second. If you do
val x = Foo()
inside the context of a @Composable function,
Foo()
will be re-called on every recomposition and therefore if you’re saving anything in there, it will be overwritten. If you are not inside a composable function then you just never need
remember
. Hence the examples where inside plain classes you can just do
mutableStateOf
directly. That’s how I like to think about it at least.
d
Thanks! Nice explanation!