Android MVP WeakRefrence

In mvp we save this activity link in a weak link. WeakReference<Activity> view = new WeakReference<Activity>(activity); If we lose the link. can we return it?

+6
source share
2 answers

If you lost the link to your Activity , it means that the activity was garbage collected and it no longer exists. You cannot return that which does not exist.

Ex. If this happens due to a configuration change, it means that a new Activity been created.

You need a way to bind the newly created view to the same presenter.

If you are looking for libraries to help you, check out mosby and nucleus .

+4
source

I don’t think you should keep a link to Activity in MVP at all - it doesn’t matter whether it's hard or weak!

I assume that you are saving this link in Presenter . To truly separate the layers, you must create an interface that describes your View ( Activity ) and use it instead of activity.

So you would do:

 public interface LoginView { displayUsernameError(String error); displayPasswordError(String error); openMainScreen(); } 

Your Activity should implement the interface from above.

 public class LoginActivity implements LoginView { ... } 

In your presenter, you must:

 class LoginPresenter { private LoginView mView; public LoginPresenter(LoginView view) { mView = view; } public onLoginButtonClicked(String username, char[] password) { ... mView.openMainScreen(); } } 

The immediate benefits of this are:

  • The different layers are really untied. You can change your Activity (let's say you decide to use Fragments ) without touching your Presenter .

  • Your host is fully tested with JUnit ! There is no need to use anything fantastic to verify that your interactions are correct, just Mockito to make fun of LoginView .

Another point - are you sure you want your Presenter survive your View ? There are situations where this cannot be avoided, but in most cases they have the same lifespan - when the View destroyed, Presenter should also be.

+1
source

All Articles