sockeqwe / mosby

A Model-View-Presenter / Model-View-Intent library for modern Android apps
http://hannesdorfmann.com/mosby/
Apache License 2.0
5.49k stars 841 forks source link

Surviving Presenter with static map #210

Closed goransipic closed 7 years ago

goransipic commented 7 years ago

When you write class (IdBasedActivityMvpDelegate) on your tutorial page your are telling that is problem with this implementation is memory management. When does a Presenter gets removed from this map? But that question is obvious using isConfigurationChange() method of Activity you can easily know when to release presenter from Map.

public class IdBasedActivityMvpDelegate<V extends IdBasedMvpView, P extends MvpPresenter<V>>
   implements ActivityMvpDelegate {

 // Every view gets an unique id
 private static int lastViewId = 0;

 // Map to store presenter
 private static Map<Integer, MvpPresenter> presenterMap = new HashMap<>();

 // The reference to the Activity
 private MvpDelegateCallback<V, P>  delegateCallback;

 public ActivityMvpDelegateImpl(MvpDelegateCallback<V, P> delegateCallback) {
   this.delegateCallback = delegateCallback;
 }

 // Called from Activity.onCreate()
 @Override
 public void onCreate(Bundle bundle) {

   // Returns 0 if no view id is assigned
   int viewId = bundle.getInt("MvpViewId");

   MvpPresenter presenter = presenterMap.get(viewId);

   if (presenter == null){
     // No presenter in Map --> View starting first time
     // so create a new presenter and put it into presenterMap
     presenter = delegateCallback.createPresenter();

     viewId = ++lastViewId;
     presenterMap.put(viewId, presenter);
   }

   V view = delegateCallback.getMvpView();

   view.setViewId(viewId);
   view.setPresenter(presenter);
   presenter.attachView(view);
 }

 @Override
 public void onSaveInstanceState(Bundle outState) {
   int viewId = delegateCallback.getMvpView().getViewId();
   outState.putInt("MvpViewId", viewId);
 }

 @Override
 public void onDestroy() {
   delegateCallback.getPresenter().detachView(true); // true = presenter retains instance state
 }
}
sockeqwe commented 7 years ago

Yes that's true, but what is your question?

Btw. Mosby 3 uses such a static map delegate (more or less)