Colton Idle
03/13/2023, 6:34 PMval buttonClick: (() -> Unit)? =
if (state.value?.foo == null) {
null
} else {
{ //some lambda content }
}
MyComposable(clickEvent = buttonClick)
Do I need to wrap this in a remember or something?Colton Idle
03/13/2023, 6:59 PMFrancesc
03/13/2023, 7:59 PMrememberUpdatedState
Colton Idle
03/13/2023, 8:25 PMmyanmarking
03/13/2023, 10:36 PMStylianos Gakis
03/13/2023, 11:42 PMYou dont need rememberupdatedstate for correctnessYou may very well need
rememberUpdatedState
for correctness. In some cases you may be referencing the old lambda if you don’t key properly or don’t use rememberUpdatedState.
It can be seen in as simple of an example as this (from a case where I had to do this myself):
fun Foo(lambda: () -> Unit) {
Box() {
Something(
Modifier.pointerInput(Unit) {
detectTapGestures {
lambda()
}
}
)
}
}
If you don’t change this to this
fun Foo(lambda: () -> Unit) {
val updatedLambda = rememberUpdatedState(lambda)
Box() {
Something(
Modifier.pointerInput(Unit) {
detectTapGestures {
updatedLambda()
}
}
)
}
}
you will be calling the lambda passed on the first composition to Foo, and not the most updated one.Csaba Szugyiczki
03/14/2023, 8:35 AMpointerInput
Modifier. In Material UI element implementations usually the lambda is the key that will be called inside the modifier to prevent using the old lambda reference.
Your solution using rememberUpdatedState
however is more performant as it is not triggering recomposition of the element on which pointerInput is used, so if you change your lambda frequently it might be a better solution.
Not sure if not using the lambda for the pointerInput Modifier could lead to “incorrect” behaviour tho 🤔Stylianos Gakis
03/14/2023, 8:49 AMCsaba Szugyiczki
03/14/2023, 8:54 AM