Does Jetpack Compose automatically clear lambda captures when a composable exits the composition tree?
27.5K reputation · 23 Aug 2024, 17:48 UTC
Memory Leak Risk from Lambda Captures in Jetpack Compose
In Compose, a composable can capture references in lambda parameters. When the composable is removed from the composition tree, the runtime does not expose a public mechanism to nullify these references, raising the possibility that objects referenced by the lambda remain reachable and cause a memory leak, especially in navigation scenarios where screens are frequently created and destroyed.
Current Compose releases (up to 1.5.x) provide no documented cleanup behavior for lambda captures, and the runtime does not expose an API to query retained composables. Developers must therefore rely on external profilers to detect leaks.
Given these constraints, the key open question is whether the Compose runtime will automatically clear references held by lambda captures when a composable exits the composition tree, and if not, what pattern should be used to guarantee timely cleanup.
Does the Compose runtime automatically nullify references captured in lambdas when a composable is removed from the composition tree? Which lifecycle integration pattern best ensures that ViewModel and lambda captures are released in complex navigation flows?