Observable.create { emitter ->
emitter.onNext("haha")
emitter.onComplete()
}.subscribe({ resuelt ->{
println("subscribe resuelt = $resuelt")
}
},{
})
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;
}
LambdaObserver代理了onNext, onError, onComplete, onSubscribe四个基本函数接口实现。
核心启动方法 subscribeActual(observer);抽象方法
所有的Obseable都是实现了此方法。
public final void subscribe(Observer<? super T> observer) {
ObjectHelper.requireNonNull(observer, "observer is null");
try {
observer = RxJavaPlugins.onSubscribe(this, observer);
ObjectHelper.requireNonNull(observer, "Plugin returned null Observer");
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;
}
}
我们看create创建的类ObservableCreate
public static <T> Observable<T> create(ObservableOnSubscribe<T> source) {
ObjectHelper.requireNonNull(source, "source is null");
return RxJavaPlugins.onAssembly(new ObservableCreate<T>(source));
}
他实现了 subscribeActual方法。
@Override
protected void subscribeActual(Observer<? super T> observer) {
CreateEmitter<T> parent = new CreateEmitter<T>(observer);
observer.onSubscribe(parent);
try {
source.subscribe(parent);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
parent.onError(ex);
}
}
创建一个CreateEmitter发射器包装了观察者,
source.subscribe(parent); source就是我们传递进来的实现ObservableOnSubscribe的逻辑,然后由我们调用Emitter的.next,这里就是 CreateEmitter.next,最后调用到LambdaObserver.next方法,执行回调函数
每个 Observable的实现类持有了上游数据源ObservableSource,Observable可以不断嵌套形成Observable的数据流。 在subscribe方法触发时,将会从最下游的Observable的 subscribeActual方法执行逻辑,并调用上游的subscribeActual方法,直到最顶部的数据源,执行然后执行onNext逻辑,发射数据给下游观察者,最终到达观察者LambdaObserver,调用使用方的观察者