I was using CameraX on our current project and getting some ridiculous crashes at
fragments that implements camera preview use case, also noticed that Android studio profiler tool gives memory leak warning for those fragments. So I tried to test it on official sample and I'm experiencing same leak also in
this official camerax sample. My test devices are Samsung galaxy a01 and Samsung m11.
To reproduce this leak, you just need to change
this line to app:popUpToInclusive="false" so when back button pressed, a fragment should be exist to prevent closing the application.
After changing that line, launch the app, give camera permissions, it will navigate to CameraFragment, then just press the back button. At this point, the fragment must be completely destroyed and the usecases expected to be unbinded. After all of that, if you take a look at the profiler and capture the heap dump, surprisingly, you will see CameraFragment is not destroyed and android studio shows a warning about the leak.
In the example code I just changed a single line on the nav_graph as I mentioned, nothing changed on camera implementation logic. Actually, this is a scenario that can be repeated with various examples. I see that the fragment remains in memory in every scenario where I just use the bindToLifecycle() method with the camera preview use case and then try to pop the fragment.
Is it possible to use the preview use case without a leak? I would appreciate it if you could help.