Duncan Lukkenaer
Duncan Lukkenaer

Reputation: 14004

How to memoize a lambda function in Jetpack Compose like useCallback

I'm trying to implement a memoized callback function in Jetpack Compose, similar to React's useCallback.

For example I'd like to use this to create a submit lambda function that contains the logic for submitting a form, but I don't want this lambda to be recreated on each recomposition. This should only be recreated when its dependencies change.

Does something like this exist?

Upvotes: 10

Views: 6004

Answers (2)

chuckj
chuckj

Reputation: 29635

Lambda memoization is done automatically by the compiler by generating a remember call implicitly based on the stable values captured by the lambda. You only need remember explicitly if one or more of the captured values is not considered stable by the compiler.

Upvotes: 13

Duncan Lukkenaer
Duncan Lukkenaer

Reputation: 14004

The normal remember/rememberSaveable functions can be used for this. This will only recreate the lambda function when the given dependencies change.

val submit = rememberSaveable(dependency1, dependency2) {
    {
        // Logic here
    }
}

submit()

Upvotes: 0

Related Questions