subscribe()源码解析

基于rxjava1.1.0

用例代码↓
    Observable observable1 = Observable.create(new Observable.OnSubscribe() {
        ⑤
        public void call(Subscriber subscriber) {
            subscriber.onNext("1");
            subscriber.onCompleted();
        }
    });
    Subscriber subscriber1 = new Subscriber() {
        @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 subscriber) {
        return Observable.subscribe(subscriber, this);
    }

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

④
public  OnSubscribe onSubscribeStart(Observable observableInstance, final OnSubscribe onSubscribe) {
        return onSubscribe;
    }

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

你可能感兴趣的:(subscribe()源码解析)