I decided it was high time I learned how to use Leak Canary to detect Leaks within my apps, and as I always do, I tried to implement it in my project to really understand how to
If the adapter lives any longer than the RecyclerView does, you've got to clear the adapter reference in onDestroyView:
@Override
public void onDestroyView() {
recyclerView.setAdapter(null);
super.onDestroyView();
}
Otherwise the adapter is going to hold a reference to the RecyclerView which should have already gone out of memory.
If the screen is involved in transition animations, you actually have to take this one step further and only clear the adapter when the view has become detached:
@Override
public void onDestroyView() {
recyclerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
// no-op
}
@Override
public void onViewDetachedFromWindow(View v) {
recyclerView.setAdapter(null);
}
});
super.onDestroyView();
}