由于源码版本不同,可能会有所差别
create:
创建一个新的Observable
map :
也是创建了一个新的Observable
OnSubscribe 是create里面的参数
@Deprecated
public static Observable create(OnSubscribe f) {
return new Observable(RxJavaHooks.onCreate(f));
}
public final Observable map(Func1 super T, ? extends R> func) {
// 这个this是我们通过create方法创建的Observable
return unsafeCreate(new OnSubscribeMap(this, func));
}
public final class OnSubscribeMap implements OnSubscribe {}
OnSubscribe 就是OnSubscribeMap对象,因为它实现了OnSubscribe接口
public static Observable unsafeCreate(OnSubscribe f) {
// 这里会修改this这个引用
return new Observable(RxJavaHooks.onCreate(f));
}
public final Subscription subscribe(final Observer super T> observer) {
// 构建subscribe对象
return subscribe(new ObserverSubscriber(observer));
}
this 这个对象是我们上面的Observable对象,即最后一次调用创建的Observable对象,这里是OnSubscribeMap
public final Subscription subscribe(Subscriber super T> subscriber) {
return Observable.subscribe(subscriber, this);
}
static Subscription subscribe(Subscriber super T> subscriber, Observable observable) {
// 这里直接调用了我们上面传入的Observable即OnSubscribeMap的call方法
RxJavaHooks.onObservableStart(observable, observable.onSubscribe).call(subscriber);
return RxJavaHooks.onObservableReturn(subscriber);
}
@Override
public void call(final Subscriber super R> o) {
MapSubscriber parent = new MapSubscriber(o, transformer);
o.add(parent);
// source即Observable,即旧的Observable
source.unsafeSubscribe(parent);
}
subscriber OnSubscribeMap$MapSubscriber
public final Subscription unsafeSubscribe(Subscriber super T> subscriber) {
// 这里调用onSubscribe的call方法,其实就是调用了在create时传入的OnSubscribe的call方法
// 同把时OnSubscribeMap$MapSubscriber对象的引用作为call方法的参数传入
// 这样, 在调用subscriber.onNext,onComplete即调用刚才了MapSubscriber中去了
RxJavaHooks.onObservableStart(this, onSubscribe).call(subscriber);
return RxJavaHooks.onObservableReturn(subscriber);
}
Observable.
create((Observable.OnSubscribe) subscriber -> {
LogUtils.loge("OnSubscribe call ... ");
if (!subscriber.isUnsubscribed()) {
LogUtils.loge("subscriber.onNext ... ");
subscriber.onNext("10");
subscriber.onCompleted();
}
}).
map(s -> {
return Integer.valueOf(s);
}).
subscribe(new Observer() {
@Override
public void onCompleted() {
LogUtils.loge("Observer onCompleted ... ");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Integer integer) {
LogUtils.loge("Observer onNext value = " + integer + " , cls type = " + integer.getClass());
}
});
@Override
public void onNext(T t) {
R result;
// map操作符的func1,即对传入的数据进行转换
result = mapper.call(t);
// actual 为ObserverSubscriber,即调用到了Observer的onNext方法
actual.onNext(result);
}
@Override
public void onNext(T t) {
// 调用observer的onNext方法
observer.onNext(t);
}