Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVP, set the view of the presenter to null on destroy?

I am currently trying to implement the MVP pattern on Android. However, I came to think about memory leaks (since the presenter holds a reference to the activity - the view). My question is, should I set the view of the presenter to null say onDestroy of the activity?

This is my main activity:

public class MainActivity extends AppCompatActivity implements MainView {
private Button loadUser;
private TextView mTextView;
@Inject
IMainPresenter mPresenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setUpViews();

    ((MyApp) getApplication()).getAppComponent().inject(this);
    mPresenter.setView(this);
}

private void setUpViews() {
    loadUser = (Button) findViewById(R.id.getUserBtn);
    loadUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mPresenter.loadUserName(2);
        }
    });
    mTextView = (TextView) findViewById(R.id.userNameTextView);
}

@Override
public void setUserName(String userName) {
    mTextView.setText(userName);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mPresenter.setView(null);
}
}
like image 850
Georgi Koemdzhiev Avatar asked Dec 18 '16 00:12

Georgi Koemdzhiev


1 Answers

I'll assume that you are using an Injection library (probably Dagger looking at your code) and the Presenter is annotated with @Singleton? If so, then setting to null is one option (and yes you should not be retaining an Activity instance on configuration changes).

Another option is to use a WeakReference in your Presenter that way setting to null is not required, although setting to null is more explicit.

You might consider using Interfaces with your Presenter rather than exposing the whole Activity to the Presenter instance - you may already be doign something like this, but not 100% clear from code provided.

like image 60
Mark Avatar answered Oct 19 '22 21:10

Mark