Android RXjava实现子线程做耗时操作,比new Thread和handler更香
1.首先是在build.gradle里面引用下面两个库
implementation ‘io.reactivex.rxjava2:rxandroid:2.0.1’
implementation ‘io.reactivex.rxjava2:rxjava:2.0.7’
2.创建CompositeDisposable 。CompositeDisposable是一个存放Disposable的集合,它是一个容器
CompositeDisposable compositeDisposable = new CompositeDisposable();
3.创建Observable
//创建子线程
Observable operationObservable = Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
//耗时操作代码todo
emitter.onNext(1);
emitter.onComplete();
}
}).subscribeOn(Schedulers.io());//线程调度器
operationObservable.subscribe(new io.reactivex.Observer() {
@Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
@Override
public void onNext(Integer integer) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
4.销毁容器
@Override
protected void onDestroy() {
super.onDestroy();
compositeDisposable.clear();
}