MVP, set the leading view to zero on destruction?

I'm currently trying to implement an MVP pattern on Android. However, I thought about a memory leak (as the presenter refers to an activity - a view). My question is, should I set the opinion of the host to null, for example onDestroy?

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); } } 
+6
source share
3 answers

I always liked it, I mean that I always set the null view in the onDestroy() method. I am trying to use the LightCycle library to avoid having to code all this boilerplate code. Here's an article that explains Fernando Say Pure architecture . This is the widely used MVP architecture (I worked for several companies that use this template), there you can see that it also sets the null view in the onDestroy() method. Let me know if I can help you.

+1
source

I assume that you are using the Injection library (perhaps a dagger looking at your code) and Presenter annotated using @Singleton ? If so, then setting the value to zero is one of the parameters (and yes, you should not save the Activity instance when changing the configuration).

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

You can use the interfaces with your Presenter , and not expose the entire Activity a Presenter instance - you can already do something like this, but not 100% clear the code provided.

+4
source

Could not make the presenter life cycle https://developer.android.com/topic/libraries/architecture/lifecycle.html ? The host could then be responsible for setting the view to null when onDestroy () is called in the view.

+2
source

Source: https://habr.com/ru/post/1013249/


All Articles