I’m playing a little bit with remeberUpdatedState ...
# compose
m
I’m playing a little bit with remeberUpdatedState and I found some mechanisms that I do not fully understand. I have two composable functions. 1. The first one is using a mutableStateOf which is used within
LaunchedEffect
. When the state changes then the value of this state in the
LaunchedEffect
contains the correct updated value. 2. Second one is basically a refactoring of the first one but the state is moved outside of the composable and then is passed as the parameter. When the state change outside of the composable then the
LaunchedEffect
does not contain correct updated value but the initial value. I know that in the second case it can be fixed by using rememberUpdateState, but I do not understand why is this happening? Can somebody explain it to me please? The code samples are in the Thread
Copy code
@Composable
fun Sample1() {
    val textThatCanBeChanged = remember { mutableStateOf("") }
    LaunchedEffect(Unit) {
        delay(2000)
        println("Result ${textThatCanBeChanged.value}")
    }
    // ... the state will be changed somewhere here
}

@Composable
fun Sample2(textThatCanBeChanged: String) {
    LaunchedEffect(Unit) {
        delay(2000)
        println("Result $textThatCanBeChanged")
    }
    // ... the state will be changed outside of this composable
}
a
State<T>
is a value holder, which means that it is the same instance that holds different values. `String`s are immutable so different strings are different instances. Lambda captures instances, so the captured value holder always holds the latest value but the captured immutable string instance won't be updated.
💪 1
m
Of course, that totally makes sense, thanks