Context Anti-Pattern: Outliving It

Suppose that we had an activity that looked like this:

private lateinit var doNotDoThis: View

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_main)
    
    doNotDoThis = showElapsed // from the SimpleBoom layout, showElapsed is a widget
  }
}

We take a widget from our activity’s layout and we assign it to a global property.

On the surface, this may not seem all that bad. However, when the activity is destroyed — due to a configuration change, BACK button press, etc. — we now have a memory leak.

Each widget holds a reference to the activity that created it. In this case, doNotDoThis has a reference back to our MainActivity. Since doNotDoThis is global in scope, that widget cannot be garbage collected. And since the doNotDoThis reference prevents the widget from being garbage collected, it prevents the destroyed activity from being garbage collected.

Fortunately, Android Studio will complain if you try to do this sort of thing.

In general, be very careful about having objects that are tied to some Context outlive the Context itself. This can include forking a background thread that has a reference to a Context, as that Context cannot be garbage collected until the thread terminates.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.