Android, Kotlin lambdas, Leak Canary and Memory Leaks

We use LeakCanary to detect and avoid memory leaks in our android app.

Often activities/fragments need to invoke async methods on objects that expect onSuccess/onError/onComplete callbacks.

These callbacks often need to execute on uiThread and I am assuming they have an implicit reference to this ( which is the activity/fragment ) because of the inner class created for the callback lambda

These async methods take time and when they return, the activity could be non existent and LeakCanary often detects memory leaks at these points.

What can I do to make sure that these async methods don’t hold onto the activity instance ( this ) if it has been destroyed ?

5 Likes