https://kotlinlang.org logo
#compose
Title
# compose
t

theapache64

03/13/2022, 11:40 AM
[ SOLVED] Subject:
rememberUpdateState
I’ve seen most of the
@Composables
are using
rememberUpdateState
before invoking a lambda. For eg,
BackHandler
internally calling
rememberUpdateState
on
onBack
lambda,
clickable
modifier calls on
onClick
lambda. Does that mean we should wrap all lambda with
rememberUpdateState
before invoking ? 🤔 If that’s the case, why can’t compiler do it for us? #possibly_a_stupid_question
👍 1
a

Albert Chang

03/13/2022, 11:47 AM
Have you checked the doc? I think it explains when you need to use
rememberUpdatedState
quite clearly.
t

theapache64

03/13/2022, 11:59 AM
@Albert Chang Yes. I already read that doc. That explains one of the usecases of
rememberUpdateState
with
LaunchedEffect
. But what am asking is, basically we use
rememberUpdateState
to get the latest value (or to avoid stale value). Is there a scenario where we need to access the stale value? 🤔
a

Albert Chang

03/13/2022, 12:04 PM
The point is whether there is a long-living lambda (or function) that captures the value. If there isn't such a lambda, there is no need to use
rememberUpdatedState
.
t

theapache64

03/13/2022, 12:09 PM
Hmm. but Lambdas are mostly long-living functions or mostly used at later time (or after the composition). For example,
onClick
,
onBack
etc. So lambas without
rememberUpdatedState
should be very rare?
a

Albert Chang

03/13/2022, 12:15 PM
No, most lambdas are not long-living. In a composable function, if the dependencies of a lambda (i.e. the variables it captures) change, a new lambda instance will be created.
By saying long-living I mean it survives recomposition.
t

theapache64

03/13/2022, 12:34 PM
okay, so basically, I only need to use
rememberUpdatedState
if and only if am accessing a lambda in an area where recomposition can’t be reached. For example,
remember
,
LaunchedEffect
, etc.. is that what you’re saying ?
a

Albert Chang

03/13/2022, 12:35 PM
Yep. But for
remember
, it's better to just use it as a key.
t

theapache64

03/13/2022, 12:37 PM
ahaa.. got it.
so here they used
rememberUpdateState
because its easier better than recreating the
DisposableEffect
?
i mean, if the code is something like this
they don’t need
rememberUpdateState
here.
a

Albert Chang

03/13/2022, 12:43 PM
Yeah
OnBackPressedDispatcher
is designed that way.
t

theapache64

03/13/2022, 12:44 PM
Got it. thank you so much for bearing with me 😄
👍 1
r

rocketraman

03/14/2022, 1:47 AM
See also related DX feature request: https://issuetracker.google.com/issues/217570480
3 Views