Search code examples
androidmemory-managementmemory-leaksweak-references

Do I need to use a WeakReference for circular dependency?


We're talking Android here. We've modeled our architecture using Model-View-Presenter approach, and we hit an issue regarding weak references.

Quick Info:

  • Presenter handles logic, network calls, etc.
  • Views handles showing data on screen, displaying loading bars, etc.

The Activity/Fragment classes hold a reference to the presenter. The presenter classes hold a reference to the view classes.

Our view clases are actually interfaces usually implemented by Activity/Fragment. This means a circular dependency between the Activity/Fragment -> presenter and presenter -> view (an Activity/Fragment). For this reason, we made the presenter hold a weak reference to the view (Activity/Fragment).

Today we needed to use 2 views in the same Activity (to display different model-data), so we didn't implements it on the Activity but created 2 anonymous class. This ended up in the presenter losing the view's references (because it's a weak reference).

Now we're evaluating 2 posibilities:

  1. We don't really need the presenters to hold a WeakReference on the View cause this type of circular dependency won't leak memory.
  2. Instead of using anonymous classes, we hold a references on the Activity (so both presenter and activity have a reference to view) just for the sake of it not getting deallocated (which feels smelly).

Which one is it, do we need the presenter to hold the view as a weak reference?


Solution

  • The answer is 1 - you don't need a WeakReference in the presenter in this case. I'm using the same pattern successfully. No memory leaks occur - when the activity gets GCed the presenter goes with it. But there might be other types of problems - if you keep somewhere (for example in AsyncTask) hard reference to the presenter.