RxJava:在Android MVP中自动取消订阅

时间:2016-03-16 16:21:41

标签: android rx-java mvp

我在Android应用中使用RxJava / Retrofit和MVP模式。

现在我希望在xxxPresenter销毁Activity/Fragment时清除oom

Presenter简单代码:

public class LoginPresenter {

    private LoginView mLoginView;
    private LoginMode mLoginMode;
    private Subscriber mLoginSubscriber;

    public LoginPresenter(LoginView loginView) {
        this.mLoginView = loginView;
        mLoginMode = new LoginMode();
    }

    void login(String userName, String pwd) {
        mLoginSubscriber = new Subscriber() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Object o) {
                if (mLoginView != null) {
                    mLoginView.onLoginSuccess();
                }
            }
        };
        mLoginMode.login(userName, pwd, mLoginSubscriber);
    }

    void destory() {
        mLoginView = null;
        mLoginSubscriber.unsubscribe();
    }

}

当Activity / Fragment destory将调用presenter的destory()方法时

我的问题是:

如果主持人有更多的网络请求,我会收到很多订阅者,有什么办法让订阅者在Activity/Fragment失败时自动取消订阅?

1 个答案:

答案 0 :(得分:6)

我认为你需要的是CompositeSubscription。它是订阅的容器,允许您一次取消订阅。

public class LoginPresenter {

    private LoginView mLoginView;
    private LoginMode mLoginMode;
    private CompositeSubscription mSubscriptions;

    public LoginPresenter(LoginView loginView) {
        this.mLoginView = loginView;
        mLoginMode = new LoginMode();
        mSubscriptions = new CompositeSubscription();
    }

    void login(String userName, String pwd) {
        Subscription loginSubscriber = new Subscriber() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Object o) {
                if (mLoginView != null) {
                    mLoginView.onLoginSuccess();
                }
            }
        };
        mLoginMode.login(userName, pwd, loginSubscriber);
        mSubscriptions.add(loginSubscriber);
    }

    void destory() {
        mLoginView = null;
        mSubscriptions.unsubscribe();
    }

}