79253421

Date: 2024-12-05 04:43:06
Score: 1
Natty:
Report link

This issue is resolved with Strong Skipping Mode, which is enabled by default starting from Kotlin 2.0.20.

However, to give you a brief explanation, the root of the problem lies in Lambda memoization.

In Jetpack Compose: • All lambdas are stable by default. • With Strong Skipping Mode enabled, lambdas with unstable captures are also memoized. This means that all lambdas written in composable functions are now automatically remembered.

Why does this happen?

The issue arises from how Compose handles recompositions.

In Jetpack Compose, recomposition occurs when a Composable’s input parameters change.

Here, viewModel::doNothing is a member reference. When passed to the TopBar Composable, it’s evaluated to an object that holds the function reference internally. While this may seem constant, Compose doesn’t guarantee that viewModel::doNothing is referentially stable. As a result, any updates to the deviceList cause Compose to treat viewModel::doNothing as a new value, leading to recompositions.

From the Android documentation:

Without memoization, the runtime is much more likely to allocate a new lambda to any Composable that takes a lambda parameter during recomposition. As a result, the new lambda has parameters that are not equal to the last composition. This results in recomposition.

Note: A common misconception is that lambdas with unstable captures are themselves unstable objects. This is not true. The Compose compiler always considers lambdas to be stable. However, with Strong Skipping Mode disabled, the compiler does not memoize them, and the runtime allocates them during recomposition. As such, lambdas with unstable captures cause Compose not to skip Composables because they have unequal parameters.

Why does wrapping doNothing in a variable (e.g., doNothingVal) prevent recompositions?

When you wrap the function in a variable, you’re creating a stable lambda. Compose recognizes that this variable reference does not change and treats it as referentially stable, preventing unnecessary recompositions.

Additional Resources

I highly recommend checking out the Android documentation and articles about stability and recomposition in Jetpack Compose for a deeper understanding of these concepts:

Reasons:
  • RegEx Blacklisted phrase (0.5): any updates
  • Long answer (-1):
  • No code block (0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: hasan.z