Tash
10/19/2021, 12:16 AM// Using derivedStateOf
fun nameA(name: String): State<String> {
return derivedStateOf { "Hello $name" }
}
// Using rememberUpdatedState
@Composable
fun nameA(name: String): State<String> {
return rememberUpdatedState("Hello $name")
}
mattinger
10/19/2021, 12:19 AMAlbert Chang
10/19/2021, 12:43 AMderivedStateOf
only runs the calculation when the states (name
here) read in the lambda change. rememberUpdatedState
runs the calculation on every recomposition. Also if you are using derivedStateOf
in a composable function, you should always remember
it.rememberUpdatedState
behaves. You are probably talking about rememberSavable
.mattinger
10/19/2021, 12:57 AMTash
10/19/2021, 8:07 AMimportant distinction 👍🏼 so basically, with usage we’re looking at:only runs the calculation when the states (derivedStateOf
here) read in the lambda change.name
runs the calculation on every recompositionrememberUpdatedState
// Using derivedStateOf + usage
@Composable
fun Content(name: String) {
val greeting by remember { greeting(name) }
Text(greeting)
}
fun greeting(name: String): State<String> {
return derivedStateOf { "Hello $name" }
}
// Using rememberUpdatedState + usage
@Composable
fun Content(name: String) {
val greeting by greeting(name)
Text(greeting)
}
@Composable
fun greeting(name: String): State<String> {
return rememberUpdatedState("Hello $name")
}
Adam Powell
10/19/2021, 1:45 PMTash
10/19/2021, 5:56 PMAdam Powell
10/19/2021, 5:59 PMrememberUpdatedState
🙂Tash
10/19/2021, 6:02 PMwe debated quite a bit about this decision and how lambda capture updates like this should happen/be allowed, and we chose to be more explicit and more closely match how Kotlin behaves elsewhereah, I see. makes sense 👍🏼
fun greeting
that uses derivedStateOf
won’t actually be doing anything…just just going to create the string once…and thats it…fun greeting
with rememberUpdatedState
will ensure that the returned state will always contain the latest name
that the function was called with