I've got a silly question. I have a state that hav...
# compose
a
I've got a silly question. I have a state that have a default value passed as parameter. In general, I want to be managed inside the component, but if the default value is changed, I wand inner state to be reset to the new default value. Which is the simplest way to do that? Construct like this works, but it looks ugly:
Copy code
var cachedValue by remember { mutableStateOf(initialViewPoint) }
    var viewPoint by remember { mutableStateOf(initialViewPoint) }

    if (cachedValue != initialViewPoint) {
        viewPoint = initialViewPoint
        cachedValue = initialViewPoint
    }
z
Im fairly certain you could use
key(value){}
around your content, whenever value changes then the inner remember, etc, will be reset as if it was the first time it was invoked.
a
It works the same way as
remember(initialViewPoint){}
and it is very strange because it does not reset the value, but instead changes the way the value is visible in some strange way. The value is different for different functions inside the composable. Maybe it is some kind of bug in compose-desktop since I am using dev version.
z
Just so that were on the same page; are you seeing that behavior even if you wrap the
cachedValue
,
viewPoint
, alongside however you make use of them, inside the
key(){}
block? As an alternative to all of this, I guess you could also specify initialViewPoint as the key for the remember calls so that they reset whenever it changes.
a
cachedValue is not needed. I've introdiced it only to reset primary value when needed. I tried to wrap remember block in key and provide key for remember. It works the same. The value of viewPoint inside the function sometimes is correct and sometimes uses the initial value passed on the first invocation. I can't see how it could be the correct behavior.
s
There are no silly questions!
z
There are quite a few remember blocks and the like in there; did you specify viewPoint as the key for all of them? Otherwise, some of them will keep their old value, which could explain why you were seeing the value being different in different scopes. Im just about to head out, but as a last suggestion; it might be a good idea to wrap the entire MapView in a
key(viewPoint) { MapView(...) }
block instead. Given that its not actually a bug (or me simply misunderstanding key completely 😅) that should give you the behavior youre looking for as well.
a
hmm... I have not checked that. Thank you, I will try
Yes, that helped. Thanks, @Zoltan Demant. It seems like one of lambdas was capturing the old value.