MVP,在销毁时将演示者的视图设置为null? [英] MVP, set the view of the presenter to null on destroy?

查看:90
本文介绍了MVP,在销毁时将演示者的视图设置为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在Android上实现MVP模式.但是,我开始考虑内存泄漏(因为演示者拥有对活动的引用-视图).我的问题是,是否应将演示者的视图设置为null,再说活动的onDestroy?

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?

这是我的主要活动:

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);
}
}

推荐答案

我总是那样,我的意思是,我总是在onDestroy()方法上将视图设置为null.我尝试使用 LightCycle 库来避免对所有样板代码进行编码.这是一篇说明Fernando Ceja的清洁架构的文章.这是一种广泛使用的MVP架构(我曾在多家使用此模式的公司中工作过),在那里您可以看到他还在onDestroy()方法中将视图设置为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 the onDestroy() method. Let me know if I can help you any further.

更新:

这个答案有点过时了,现在您可以使用Android的Jetpack工具中的LifecycleOwner类.基本上是相同的交易,但是使用不同的API.

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.

这篇关于MVP,在销毁时将演示者的视图设置为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆