Android leak pattern: subscriptions in views

Android leak pattern: subscriptions in views

Avoid memory leaks by properly handling view subscriptions

In Square Register Android, we rely on custom views to structure our app. Sometimes a view listens to changes from an object that lives longer than that view.

For instance, a HeaderView might want to listen to username changes coming from an Authenticator singleton:

public class HeaderView extends FrameLayout {
  private final Authenticator authenticator;

  public HeaderView(Context context, AttributeSet attrs) {...}

  @Override protected void onFinishInflate() {
    final TextView usernameView = (TextView) findViewById(R.id.username);
    authenticator.username().subscribe(new Action1<String>() {
      @Override public void call(String username) {
        usernameView.setText(username);
      }
    });
  }
}

onFinishInflate() is a good place for an inflated custom view to find its child views, so we do that and then we subscribe to username changes.

The above code has a major bug: We never unsubscribe. When the view goes away, the Action1 stays subscribed. Because the Action1 is an anonymous class, it keeps a reference to the outer class, HeaderView. The entire view hierarchy is now leaking, and can’t be garbage collected.

To fix this bug, let’s unsubscribe when the view is detached from the window:

public class HeaderView extends FrameLayout {
  private final Authenticator authenticator;
  private Subscription usernameSubscription;

  public HeaderView(Context context, AttributeSet attrs) {...}

  @Override protected void onFinishInflate() {
    final TextView usernameView = (TextView) findViewById(R.id.username);
    usernameSubscription = authenticator.username().subscribe(new Action1<String>() {
      @Override public void call(String username) {...}
    });
  }

   @Override protected void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    usernameSubscription.unsubscribe();
  }
}

Problem fixed? Not exactly. I was recently looking at a LeakCanary report, which was caused by a very similar piece of code:

Let’s look at the code again:

public class HeaderView extends FrameLayout {
  private final Authenticator authenticator;
  private Subscription usernameSubscription;

  public HeaderView(Context context, AttributeSet attrs) {...}

  @Override protected void onFinishInflate() {...}

   @Override protected void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    usernameSubscription.unsubscribe();
  }
}

Somehow View.onDetachedFromWindow() was not being called, which created the leak.

While debugging, I realized that View.onAttachedToWindow() wasn’t called, either. If a view is never attached, obviously it won’t be detached. So, View.onFinishInflate() is called, but not View.onAttachedToWindow().

Let’s learn more about View.onAttachedToWindow():

  • When a view is added to a parent view with a window, onAttachedToWindow() is called immediately, from addView().

  • When a view is added to a parent view with no window, onAttachedToWindow() will be called when that parent is attached to a window.

We’re inflating the view hierarchy the typical Android way:

public class MyActivity {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity);
  }
}

At that point, every view in the view hierarchy has received the View.onFinishInflate() callback, but not the View.onAttachedToWindow() callback. Here’s why:

View.onAttachedToWindow() is called on the first view traversal, sometime after Activity.onStart()

ViewRootImpl is where the onAttachedToWindow() call is dispatched:

public class ViewRootImpl {
  private void performTraversals() {
    // ...
    if (mFirst) {
      host.dispatchAttachedToWindow(mAttachInfo, 0);
    }
    // ...
  }
}

Cool, so we don’t get attached in onCreate(), what about after onStart() though? Isn’t that always called after onCreate()?

Not always! The Activity.onCreate() javadoc gives us the answer:

You can call finish() from within this function, in which case onDestroy() will be immediately called without any of the rest of the activity lifecycle (onStart(), onResume(), onPause(), etc) executing.

Eureka!

We were validating the activity intent in onCreate(), and immediately calling finish() with an error result if the content of that intent was invalid:

public class MyActivity {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity);
    if (!intentValid(getIntent()) {
      setResult(Activity.RESULT_CANCELED, null);
      finish();
    }
  }
}

The view hierarchy was inflated, but never attached to the window and therefore never detached.

Here’s an updated version of the good old activity lifecycle diagram:

With that knowledge, we can now move the subscription code to onAttachedToWindow():

public class HeaderView extends FrameLayout {
  private final Authenticator authenticator;
  private Subscription usernameSubscription;

  public HeaderView(Context context, AttributeSet attrs) {...}

  @Override protected void onAttachedToWindow() {
    final TextView usernameView = (TextView) findViewById(R.id.username);
    usernameSubscription = authenticator.username().subscribe(new Action1<String>() {
      @Override public void call(String username) {...}
    });
  }

   @Override protected void onDetachedFromWindow() {
    super.onDetachedFromWindow();
    usernameSubscription.unsubscribe();
  }
}

This is for the better anyway: Symmetry is good, and unlike the original implementation we can add and remove that view any number of times.