martinsumera
07/02/2021, 8:23 AMLaunchedEffect
. 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 Threadmartinsumera
07/02/2021, 8:23 AM@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
}
Albert Chang
07/02/2021, 9:12 AMState<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.martinsumera
07/02/2021, 10:28 AM