Erfannj En
12/03/2025, 6:25 AMapply { value = newValue } there is no problem.
@Composable
public fun <T> rememberUpdatedState(newValue: T): State<T> =
remember { mutableStateOf(newValue) }.apply { value = newValue }Alex Styl
12/03/2025, 6:30 AMAlex Styl
12/03/2025, 6:30 AMvalue = newValue can be called multiple timesErfannj En
12/03/2025, 6:44 AMMohammad Fallah
12/03/2025, 10:04 AMrememberUpdatedState 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.
@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
val currentDoWhat = rememberUpdatedState(doWhat)
then you can use currentDoWhat in LaunchedEffect.Zach Klippenstein (he/him) [MOD]
12/03/2025, 4:43 PMErfannj En
12/05/2025, 10:00 AM