如何取消订阅rxJava请求

时间:2017-04-08 15:09:00

标签: java android rx-java2

我有以下类,我想返回Subscription对象或其他东西,所以我可以从我引用subscribe()方法的地方取消请求,但是subscribe(observer)返回void! 我怎么能这样做?

public abstract class MainPresenter<T> {
protected <T> Disposable subscribe(Observable<T> observable, Observer<T> observer) {
observable.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(observer);

}

[新更新] 我用这种方式暂时,我在等待更好的解决方案:

    protected <T> DisposableMaybeObserver subscribe(final Maybe<T> observable,
                                                final Observer<T> observer) {
    return observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableMaybeObserver<T>() {
                @Override
                public void onSuccess(T t) {
                    observer.onNext(t);
                }

                @Override
                public void onError(Throwable e) {
                    observer.onError(e);
                }

                @Override
                public void onComplete() {
                    observer.onComplete();
                }
            });
}

[新更新2 ] [![截图] [https://i.stack.imgur.com/mioth.jpg]]

[新版本3 ] [Screenshot2] 1

1 个答案:

答案 0 :(得分:5)

您应该使用subscribeWith

private Disposable mDisposable;

public abstract class MainPresenter<T> {
protected Disposable subscribe(Observable<T> observable, DisposableObserver<T> observer) {
mDisposable = observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(observer);

return mDisposable;

}

然后当你需要:

if (mDisposable != null && !mDisposable.isDisposed()) {
    mDisposable.dispose();
}

希望这有帮助。