If I want to define a local function inside my composable, my first intuition tells me to store it in a val and remember it. But I wonder what is the practical difference between the two? And if I am using parameters that come into the composable, is there a way to shoot myself in the foot by accidentally having it reference an old value of those parameters?
Copy code
@Composable
fun Foo(someParameter: String) {
// Option #1
val myFunction: () -> Unit = remember(someParameter) {
{
doSomething(someParameter)
}
}
// Option #2
fun myFunction {
doSomething(someParameter)
}
// Usage of #1
OtherComposable(callback = myFunction)
// Usage of #2
OtherComposable(callback = ::myFunction)
}
@Composable
fun OtherComposable(callBack: () -> Unit) { ... }
a
Albert Chang
03/16/2024, 11:17 AM
Not sure about local function, but option #1 is the same as the lambda only (without remember), as Compose will automatically memoize the lambda instance. See the “Lambda memoization” section of this post.
thank you color 1
s
Stylianos Gakis
03/16/2024, 11:22 AM
Aha right, even if the composable recomposed because I have 10 parameters for example, and I don't want the lambda to be "recreated" when the other ones change but only if the parameter I use is, I still don't need to remember it myself, I get it for free.
Provided the parameter is stable of course, until I enable strong skipping.