Issue
I'm confused, can someone explain me the difference between:
val variable by remember { mutableStateOf() }
and
val variable by rememberUpdatedState()
When I check the source code of rememberUpdatedStates
I actually see: remember { mutableStateOf() }
@Composable
fun <T> rememberUpdatedState(newValue: T): State<T> = remember {
mutableStateOf(newValue)
}.apply { value = newValue }
Solution
remember is needed when you don't want to do some heavy calculation/opearation when your composable is recomposed on the other hand sometimes your operation might change so you need to do calculation or update remembered value to be not able to use obsolete value from initial calculation.
fun <T> rememberUpdatedState(newValue: T): State<T> = remember {
mutableStateOf(newValue)
}.apply { value = newValue }
rememberUpdatedState
function is same as using remember
with mutableState
to trigger recomposition when value
changes.
@Composable
private fun Calculation(input: Int) {
val rememberUpdatedStateInput by rememberUpdatedState(input)
val rememberedInput = remember { input }
Text("updatedInput: $rememberUpdatedStateInput, rememberedInput: $rememberedInput")
}
var myInput by remember {
mutableStateOf(0)
}
OutlinedButton(
onClick = {
myInput++
}
) {
Text("Increase $myInput")
}
Calculation(input = myInput)
This is a very basic example to show how values
from remember and rememberUpdatedState change
More practical example is with lambdas
For example, suppose your app has a LandingScreen that disappears after some time. Even if LandingScreen is recomposed, the effect that waits for some time and notifies that the time passed shouldn't be restarted:
@Composable
fun LandingScreen(onTimeout: () -> Unit) {
// This will always refer to the latest onTimeout function that
// LandingScreen was recomposed with
val currentOnTimeout by rememberUpdatedState(onTimeout)
// Create an effect that matches the lifecycle of LandingScreen.
// If LandingScreen recomposes, the delay shouldn't start again.
LaunchedEffect(true) {
delay(SplashWaitTimeMillis)
currentOnTimeout()
}
/* Landing screen content */
}
In this example LaunchedEffect
is invoked once but this LandingScreen function can be recomposed and might require you to change onTimeOut
, so using rememberUpdatedState makes sure that the latest onTimeout is called after delay.
Answered By - Thracian
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.