如何使用RxJava 2的CompositeDisposable?

在RxJava

1中,有CompositeSubscription,但在RxJava2中不存在,在rxJava2中有CompositeDisposable。如何在RxJava2中使用CompositeDisposable或Disposable?

回答:

private final CompositeDisposable disposables = new CompositeDisposable();

// adding an Observable to the disposable

disposables.add(sampleObservable()

.subscribeOn(Schedulers.io())

.observeOn(AndroidSchedulers.mainThread())

.subscribeWith(new DisposableObserver<String>() {

@Override

public void onComplete() {

}

@Override

public void onError(Throwable e) {

}

@Override

public void onNext(String value) {

}

}));

static Observable<String> sampleObservable() {

return Observable.defer(new Callable<ObservableSource<? extends String>>() {

@Override

public ObservableSource<? extends String> call() throws Exception {

// Do some long running operation

SystemClock.sleep(2000);

return Observable.just("one", "two", "three", "four", "five");

}

});

}

// Using clear will clear all, but can accept new disposable

disposables.clear();

// Using dispose will clear all and set isDisposed = true, so it will not accept any new disposable

disposables.dispose();

我创建了一个示例项目来演示RxJava2的用法。在这里您可以找到示例项目-RxJava2-Android-

Samples

以上是 如何使用RxJava 2的CompositeDisposable? 的全部内容, 来源链接: utcz.com/qa/407669.html

回到顶部