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 AMmattinger
10/19/2021, 12:22 AMmattinger
10/19/2021, 12:23 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.Albert Chang
10/19/2021, 12:44 AMrememberUpdatedState
behaves. You are probably talking about rememberSavable
.mattinger
10/19/2021, 12:57 AMmattinger
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 PMAdam Powell
10/19/2021, 1:45 PMTash
10/19/2021, 5:56 PMAdam Powell
10/19/2021, 5:59 PMrememberUpdatedState
🙂Adam Powell
10/19/2021, 6:00 PMTash
10/19/2021, 6:02 PMTash
10/19/2021, 6:05 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 👍🏼
Tash
10/19/2021, 6:06 PMfun greeting
that uses derivedStateOf
won’t actually be doing anything…just just going to create the string once…and thats it…Tash
10/19/2021, 6:08 PMfun greeting
with rememberUpdatedState
will ensure that the returned state will always contain the latest name
that the function was called withTash
10/19/2021, 6:17 PM