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);
}
}
I always did like that, I mean, I always set the view to null on the
onDestroy()
method. I try to use the LightCycle library to avoid having to code all that boilerplate code. Here's an article that explains Fernando Ceja's Clean Architecture. This is an MVP architecture widely used (I've worked in a couple of companies that use this pattern), there you can see that he also sets the view to null in theonDestroy()
method. Let me know if I can help you any further.UPDATE:
This answer is kinda outdated, now you can use the LifecycleOwner class from the Android's Jetpack tools. It's basically the same deal but with different API.