Android中MVP模式的内存泄漏解决及Retrofit2、RxJava中断网络请求(二)

建立在上篇文章基础之上,我们只需要增加一个类似碎片的attach和detach就可以了。再增加一个interrupt来中断网络请求。


看看我们改造后的P

public class RequestPresenter {
    private RequestView mRequestView;
    private RequestModel mRequestModel;

    public RequestPresenter() {
        this.mRequestModel = new RequestModel();
    }

    public void clickRequest(String userName, String userPassword) {
        if (mRequestView != null) {
            mRequestView.requestLoading();
            mRequestModel.loginRequest(userName, userPassword, new Subscriber() {
                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    mRequestView.resultFailure(e.getMessage());
                    mRequestView.resultFinish();
                }

                @Override
                public void onNext(JSONObject object) {
                    mRequestView.resultSuccess(object);
                    mRequestView.resultFinish();
                }
            });
        }
    }

    public void attach(RequestView view) {
        this.mRequestView = view;
    }

    public void detach() {
        mRequestView = null;
    }

    public void interruptHttp() {
        mRequestModel.interruptRequest();
    }
}
构造方法不一样了。我们不采用构造器赋值的形式了,而是通过attach方法(就好比是set方法)

最下面多出了3个方法。attach,detach,最后还多了一个中断网络请求的操作。


我们可以进M看一下

public class RequestModel {
    private static final String BASE_URL = "http://10.19.71.204:8080/";

    private Subscription subscription;

    void loginRequest(String userName, String userPassword,
                      Subscriber subscriber) {
        subscription = (new RetrofitUtils())
                .getRetrofit(BASE_URL)
                .create(LoginAPI.class)
                .login(userName, userPassword)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    void interruptRequest() {
        subscription.unsubscribe();
        subscription = null;
    }
}
我们直接取消订阅就可以了(如果纯Retrofit,call.cancel()就可以了)


最后看看V层的onCreate和onDestory

@Override
protected void onDestroy() {
    super.onDestroy();
    presenter.interruptHttp();
    presenter.detach();
}

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

    presenter = new RequestPresenter();
    presenter.attach(this);
}

github地址:https://github.com/xubinhong/MVP2

你可能感兴趣的:(Android)