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:
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:
presenters
to hold a WeakReference
on the View
cause this type of circular dependency won't leak memory.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?
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.