观察者模式
为了方便查看Rxjava的源码,举一个最简单的使用rxjava的例子。
Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
Log.d(TAG, "subscribe: ");
emitter.onNext(1);
emitter.onNext(2);
emitter.onComplete();
}
}).subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
Log.d(TAG, "onSubscribe: ");
}
@Override
public void onNext(Integer integer) {
Log.d(TAG, "onNext: ");
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "onError: ");
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete: ");
}
});
整体结构看起来还算是比较简单,通过subscribe方法将Observable对象和Observer对象关联,但是要深究的是在这段代码背后rxjava究竟做了什么。
一切从最核心的开始,subscribe方法作为纽带,先来看看具体实现了什么。
public final void subscribe(Observer<? super T> observer) {
ObjectHelper.requireNonNull(observer, "observer is null");
try {
observer = RxJavaPlugins.onSubscribe(this, observer);
ObjectHelper.requireNonNull(observer, "The RxJavaPlugins.onSubscribe hook returned a null Observer. Please change the handler provided to RxJavaPlugins.setOnObservableSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins");
subscribeActual(observer);
} catch (NullPointerException e) {
// NOPMD
throw e;
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
// can't call onError because no way to know if a Disposable has been set or not
// can't call onSubscribe because the call might have set a Subscription already
RxJavaPlugins.onError(e);
NullPointerException npe = new NullPointerException("Actually not, but can't throw other exceptions due to RS");
npe.initCause(e);
throw npe;
}
}
RxJavaPlugins类中的方法基本上都是先把传入的对象拉去做一些其他事,然后再返回,对于整体的运行来说,基本可以忽略,这段代码中,进行了判空,然后最重要的就是将传入的observer对象传入了subscribeActual方法中。
而subscribeActual方法在Observable类中是一个抽象方法,具体实现还要看后文其实现类是怎么做的。
退回到上一步subscribe方法中,有各种各样参数的重载,但最终都会调用这个subscribe方法
public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError,
Action onComplete, Consumer<? super Disposable> onSubscribe) {
ObjectHelper.requireNonNull(onNext, "onNext is null");
ObjectHelper.requireNonNull(onError, "onError is null");
ObjectHelper.requireNonNull(onComplete, "onComplete is null");
ObjectHelper.requireNonNull(onSubscribe, "onSubscribe is null");
LambdaObserver<T> ls = new LambdaObserver<T>(onNext, onError, onComplete, onSubscribe);
subscribe(ls);
return ls;
}
将传入的各种Consumer对象封装在一个LambdaObserver对象中,然后再调用了subscribe方法,如上文subscribe方法中最终调用了subscribeActual方法,这是个抽象方法,那么具体实现就需要到Observable的子类中去找了。
那么在Observable.create方法中发生了什么呢,
public static <T> Observable<T> create(ObservableOnSubscribe<T> source