在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的用法。在这里您可以找到sample project - RxJava2-Android-Samples
关于java - 如何使用RxJava 2的CompositeDisposable?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39203791/