在RxJava 1中,有CompositeSubscription,但在RxJava2中不存在,在rxJava2中有CompositeDisposable。如何在RxJava2中使用CompositeDisposable或Disposable?
Answers:
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
CompositeDisposable
弃置后不能再使用。如果您希望将一次性生命周期与Android Activity生命周期同步,则可以通过制作一个简单的包装程序进行对应。
class AndroidDisposable {
private var compositeDisposable: CompositeDisposable? = null
fun add(disposable: Disposable) {
if (compositeDisposable == null) {
compositeDisposable = CompositeDisposable()
}
compositeDisposable?.add(disposable)
}
fun dispose() {
compositeDisposable?.dispose()
compositeDisposable = null
}
}
如何使用:
class MainActivity : AppCompatActivity() {
private disposable = AndroidDisposable()
override fun onStart() {
super.onStart()
disposable.add(/* Some disposable */)
}
override fun onStop() {
disposable.dispose()
super.onStop()
}
}