On Android, accidentally holding onto a reference such as to the Activity leads to out of memory crashes that can be hard to find showing the importance of item 7 of Joshua Bloch’s excellent book Effective Java.
One of the easiest ways to leak an activity on Android is with inner classes, especially the
Handler class. How to Leak a Context talks about this in a lot more detail as does AlertDialog causes a memory leak.
A less visible place memory leaks can occur is when using Butterknife in fragments as you must call
unbind. I wrote a small library to help detect scenarios like this when someone hasn’t called an
unbind function so if you write APIs check out leaktracker.
On reading these articles, one tip you’ll hopefully see in common is to avoid inner classes. A nicety of Kotlin is by default nested classes are implicitly
static, whereas in Java they are not, significantly reducing the chances of some of these issues. To allow a nested class to reference its outer class, you explicitly add the
inner keyword. What you still have to be aware of though is that anonymous classes, and thus also lambdas, will hold a reference to their containing class.