I was just doing some testing for one of my Composables when I found this very bizarre behaviour.
This code:-
{ //Composable-Scope
var fired = remember { false }
if(!fired) { Fire(); fired = true }
}
calls the methof Fire()
on every recomposition.
On the other hand, however,
{ //Composable Scope
var fired by remember { mutableStateOf(false) }
if(!fired) { Fire(); fired = true }
}
calls Fire()
only upon the first Composition.
If this is the intended behaviour, is there a good explanation for why remember
is not made universal? If it is not the intended behavior, I'll probably just file a bug.
CodePudding user response:
This is intended behaviour.
During the first composition value of remember
lambda is calculated and cached. On each next recomposition calling remember { ... }
will return the cached value.
In your first code block you're creating a variable, which will get the same initial value on each recomposition. You can modify it during the composition code, but on recomposition it'll be reset, as if you were not using remember
at all.
With mutable state remember does the same thing: it remembers the content of the lambda. But in this case the result is a wrapper class instance. This instance is the same between recompositions, but you can modify the value property of this object, that's why it lives thought recompositions.