subscribe()源码解析

2017-11-19  本文已影响3人  Rogge666

基于rxjava1.1.0

用例代码↓
    Observable<String> observable1 = Observable.create(new Observable.OnSubscribe<String>() {
        ⑤
        public void call(Subscriber<? super String> subscriber) {
            subscriber.onNext("1");
            subscriber.onCompleted();
        }
    });
    Subscriber<String> subscriber1 = new Subscriber<String>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        ⑥
        @Override
        public void onNext(String s) {
            Log.e("haha",s);
        }
    };
    observable1.subscribe(subscriber1);
subscribe()源码精简版
①
public final Subscription subscribe(Subscriber<? super T> subscriber) {
        return Observable.subscribe(subscriber, this);
    }

②
private static <T> Subscription subscribe(Subscriber<? super T> subscriber, Observable<T> observable) {
          subscriber.onStart();
          ③
          hook.onSubscribeStart(observable, observable.onSubscribe).call(subscriber);
          return hook.onSubscribeReturn(subscriber);
        }
    }

④
public <T> OnSubscribe<T> onSubscribeStart(Observable<? extends T> observableInstance, final OnSubscribe<T> onSubscribe) {
        return onSubscribe;
    }

执行observable1.subscribe(subscriber1);的调用顺序为①→②→③→④→⑤→⑥
在①中this为调用它的observable1
在④中返回的是observable1.onSubscribe
在③最后执行的就是observable1.onSubscribe.call(subscriber1);
在⑤中call的参数subscriber由③赋值即在call方法里执行了subscriber1.onNext("1");
至此完结

上一篇下一篇

猜你喜欢

热点阅读