一、defer语法
public Observable<Integer> getRxJavaCreateExampleData() {
return Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(ObservableEmitter<Integer> emitter) {
LogUtils.debug(TAG, "getRxJavaCreateExampleData---:" + Thread.currentThread().getName() + "--:" + 1);
emitter.onNext(1);
LogUtils.debug(TAG, "getRxJavaCreateExampleData---:" + Thread.currentThread().getName() + "--:" + 2);
emitter.onNext(2);
LogUtils.debug(TAG, "getRxJavaCreateExampleData---:" + Thread.currentThread().getName() + "--:" + 3);
emitter.onNext(3);
emitter.onComplete();
LogUtils.debug(TAG, "getRxJavaCreateExampleData---:" + Thread.currentThread().getName() + "--:" + 4);
emitter.onNext(4);
}
});
}
public void rxJavaDeferExample() {
Disposable disposable = Observable.defer(new Callable<ObservableSource<?>>() {
@Override
public ObservableSource<?> call() throws Exception {
return model.getRxJavaCreateExampleData();
}
}).subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Object>() {
@Override
public void accept(Object o) throws Exception {
LogUtils.error(TAG, "rxJavaDeferExample--:" + Thread.currentThread().getName() + "-consumer-:" + o.toString());
}
});
compositeDisposable.add(disposable);
}
日志
08-18 16:22:40.699 30806-31257/com.example.zhang D/MainModel: getRxJavaCreateExampleData---:RxCachedThreadScheduler-1--:1
08-18 16:22:40.700 30806-31257/com.example.zhang D/MainModel: getRxJavaCreateExampleData---:RxCachedThreadScheduler-1--:2
getRxJavaCreateExampleData---:RxCachedThreadScheduler-1--:3
08-18 16:22:40.700 30806-30806/com.example.zhang E/MainPresenter: rxJavaDeferExample--:main-consumer-:1
08-18 16:22:40.700 30806-31257/com.example.zhang D/MainModel: getRxJavaCreateExampleData---:RxCachedThreadScheduler-1--:4
08-18 16:22:40.700 30806-30806/com.example.zhang E/MainPresenter: rxJavaDeferExample--:main-consumer-:2
rxJavaDeferExample--:main-consumer-:3
总结
1、defer 就相当于懒加载,只有等observable 与observer建立了订阅关系时,observable才会建立
河马过河微信公众号.jpg
网友评论