Tracing simple memory leak around RecyclerView using LeakCanary

Yuichi Fujiki
5 min readFeb 5, 2019

Figuring out the object references under the hood and the importance of LeakCanary

Preface

This article is mostly meant for novice to mid level Android programmers, who haven’t really digged into LeakCanary yet. I myself used it for the first time recently after delving into Android development for a year. And I am pleasantly surprised how powerful this tool is. This is definitely a must-include tool in every project. At the same time, I was surprised how Android maintains references under the hood for RecyclerViews. With naive expectation that RecyclerView itself should avoid circular references, you can easily fall into a trap of memory leaks. (And that's exactly the kind of reason that Square guys implemented LeakCanary and everybody should use it)

How to use LeakCanary

It’s pretty simple to use LeakCanary. As instructed in the README section, you just need to 1. describe dependency in gradle and 2. write a few lines in your Application subclass. And then LeakCanary will alert you of the memory leak in your debug build.

However, as straight-forward as it sounds, there was one pitfall I got into. If you are like me and prefers to press Debug button instead of Run button on Android Studio, LeakCanary doesn’t run while you are debugging. You have to stop the debugging, and start the installed debug build from the launcher.

--

--

Yuichi Fujiki
Yuichi Fujiki

Written by Yuichi Fujiki

Technical director, Freelance developer, a Dad, a Quadriplegic, Life of Rehab