Hello everybody I'm curious about why rememberUpda...
# compose
e
Hello everybody I'm curious about why rememberUpdatedState sets the value again after remembering. It seems that without
apply { value = newValue }
there is no problem.
Copy code
@Composable
public fun <T> rememberUpdatedState(newValue: T): State<T> =
    remember { mutableStateOf(newValue) }.apply { value = newValue }
a
what is the question here?
2
it sets the value so that it maintains the latest value. the remember part will not be called again, but the
value = newValue
can be called multiple times
e
@Alex Styl thanks
👌 1
m
Hey Erfan, if you remove the apply, then it will be a simple remember without a key, it means if the value that is passed to
rememberUpdatedState
get changed in the next recomposition it won't be stored in this state. but you may argue why they didn't put a key then, the problem with
remember (key)
is that it will re-execute the block again, it means you will get a new state, it's a new reference, and if you already passed the previous state to somewhere, it won't be updated automatically, for example, assume you have a component that do something after 5 seconds from the time it comes to the composition based on one of the arguments, so after 5 seconds you will check the argument.
Copy code
@Composable
fun MySpecialComponent(doWhat : Int) {
    LaunchedEffect(Unit) {
        delay(5000)
        if (doWhat == 1) doSomething1()
        else if (doWhat == 2) doSomethingElse()
    }
}
It may look OK, but the problem is that what if the
doWhat
changes before the 5th second? e.g. the component comes to the composition with
doWhat = 1
then after 1 second it will be updated to
doWhat = 2
? you can solve this problem by
Copy code
val currentDoWhat = rememberUpdatedState(doWhat)
then you can use currentDoWhat in LaunchedEffect.
💯 4
🙌 1
z
That value set is the “update” part of “remember updated state”.
1
e
@Mohammad Fallah Thank you very much for your complete answer.
🙌 1