rxJava和rxAndroid源码解析系列二之observer订阅

接着上一篇的demo继续写下去。没看过的朋友请点击 rxJava和rxAndroid源码解析系列一之链式调用Observable嵌套

创建完Observable对象后,以后一步ObservableObserveOn.subscribe(new Observer() {.....})这一步又发生了什么呢?

接着跟踪源码。

 @SchedulerSupport(SchedulerSupport.NONE)
    @Override
    public final void subscribe(Observer 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;
        }
    }

                                                                                             <源代码片段1>

 subscribeActual(observer);这个方法,是Observable的抽象方法,由子类实现,那是谁呢,ObservableObserveOn或AbstractObservableWithUpstream,经过查找在ObservableObserveOn找到了这个实现

    @Override
    protected void subscribeActual(Observer observer) {
//scheduler是HandlerScheduler的对象,而HandlerScheduler是Scheduler的子类
        if (scheduler instanceof TrampolineScheduler) {//这个就会跳过
            source.subscribe(observer);
        } else {
            //那就从这里开始执行
            Scheduler.Worker w = scheduler.createWorker();

            source.subscribe(new ObserveOnObserver(observer, w, delayError, bufferSize));
        }
    }

                                                                                      <源代码片段2>

通过上一篇的分析source指向的是ObservableSubscribeOn的对象,scheduler是HandlerScheduler的对象,所以实际执行的是下面两行代码

                          Scheduler.Worker w = scheduler.createWorker();

            source.subscribe(new ObserveOnObserver(observer, w, delayError, bufferSize));

先看第一行

   @Override
    public Worker createWorker() {
        return new HandlerWorker(handler, async);
    }

                                                                                <源代码片段3>

HandlerWorker是HandlerScheduler的静态内部类。HandlerWorker中也有ui线程的handler。

第二行代码先看new实例对象。ObserveOnObserver是ObservableObserveOn的静态内部类,ObserveOnObserver是对observer回调的装饰和扩展,就不贴出代码了。好的,source.subscribe(new ObserveOnObserver(observer, w, delayError, bufferSize));怎么执行的呢,这个source指向的是ObservableSubscribeOn的对象,ObservableSubscribeOn也是Observable对象的子类,所以subscribe方法和<源代码片段1>一样。那就看看它实际执行订阅的代码啦

    @Override
    public void subscribeActual(final Observer observer) {
        final SubscribeOnObserver parent = new SubscribeOnObserver(observer);

        observer.onSubscribe(parent);

        parent.setDisposable(scheduler.scheduleDirect(new SubscribeTask(parent)));
    }

                                                                                  <源代码片段4>

就三行代码,就把这个线程切换和回调都完成啦?脑子里突然蹦出一句歌词,没那么简单.....那就仔细分析一下吧,第一行代码就是把传过来的ObserveOnObserver对象继续封装一下下,转变成SubscribeOnObserver,而这个类就是ObservableSubscribeOn的内部类,也进行了装饰和扩展。也没什么东东嘛,那就继续第二句observer.onSubscribe(parent);observer是ObserveOnObserver它的实例对象,我们都知道啦ObserveOnObserver是ObservableObserveOn的静态内部类,那就进去看看这个方法啦!

        @Override
        public void onSubscribe(Disposable d) {
//此时d就是传入过来的ObserveOnObserver对象嘛
// this.upstream成员变量,找了一圈,构造的时候没有它的事,为null
            if (DisposableHelper.validate(this.upstream, d)) {//if判断返回true
                this.upstream = d;
                if (d instanceof QueueDisposable) {//if判断返回false
                    @SuppressWarnings("unchecked")
                    QueueDisposable qd = (QueueDisposable) d;

                    int m = qd.requestFusion(QueueDisposable.ANY | QueueDisposable.BOUNDARY);

                    if (m == QueueDisposable.SYNC) {
                        sourceMode = m;
                        queue = qd;
                        done = true;
                        downstream.onSubscribe(this);
                        schedule();
                        return;
                    }
                    if (m == QueueDisposable.ASYNC) {
                        sourceMode = m;
                        queue = qd;
                        downstream.onSubscribe(this);
                        return;
                    }
                }
                //队列
                queue = new SpscLinkedArrayQueue(bufferSize);
                //downstream就是Observer,也就是样例代码中的new Observer(String){},就是最终回调的嘛
                downstream.onSubscribe(this);
            }
        }

                                                                                   <源代码片段5>

那就先看看这个喽DisposableHelper.validate(this.upstream, d)

    public static boolean validate(Disposable current, Disposable next) {
        if (next == null) {//next=ObserveOnObserver的对象,不为null,跳过
            RxJavaPlugins.onError(new NullPointerException("next is null"));
            return false;
        }
        if (current != null) {//current=(this.upstream=null,跳过
            next.dispose();
            reportDisposableSet();
            return false;
        }
        return true;
    }

                                                                                        <源代码片段6>

返回true, <源代码片段5>继续往下执行d instanceof QueueDisposable,这个判断,d是ObservableSubscribeOn静态内部类ObserveOnObserver的对象,那就看看这个是什么类型的

  static final class SubscribeOnObserver extends AtomicReference implements Observer, Disposable {
...............................省略
}

                                                                                      <源代码片段7>

QueueDisposable又是啥呢

public interface QueueDisposable extends QueueFuseable, Disposable {
}

                                                                                      <源代码片段8>

d instanceof QueueDisposable就只能返回fase了,if代码块跳过。<源代码片段5>继续往下执行 downstream.onSubscribe(this);

这个downstream是个成员变量,什么时候赋值的呢?

        ObserveOnObserver(Observer actual, Scheduler.Worker worker, boolean delayError, int bufferSize) {
            this.downstream = actual;
            this.worker = worker;
            this.delayError = delayError;
            this.bufferSize = bufferSize;
        }

                                                                                     <源代码片段9>

构造的时候赋值的,谁调用了呢, <源代码片段2>中赋值的,传入过来的observer是谁呢?就是这句话嘛,ObservableObserveOn.subscribe(new Observer() {.....}),才调用了 <源代码片段2>的代码段,这个不是最终回调嘛,搜嘎,

               @Override
                            public void onSubscribe(Disposable d) {
 //当前线程不就是new Thread()嘛,原来如此                               

Log.i("MainActivity","onSubscribe"+Thread.currentThread().getId()+":"+Thread.currentThread().getName());
                            }

<源代码片段4>中的 observer.onSubscribe(parent);结束了,那就继续看<源代码片段4>的最后一句代码parent.setDisposable(scheduler.scheduleDirect(new SubscribeTask(parent)));这句代码肯定会开辟一片新天地,它要肩负着线程切换和回调嘛。这句话嵌套的有点多,那我们就把他继续分解,先看看new SubscribeTask(parent),这个类也是ObservableSubscribeOn它的内部类

final class SubscribeTask implements Runnable {
        private final SubscribeOnObserver parent;

        SubscribeTask(SubscribeOnObserver parent) {
            this.parent = parent;
        }

        @Override
        public void run() {
//ObservableSubscribeOn的source,这个source指向ObservableCreate
            source.subscribe(parent);
        }
    }

                                                                              <源代码片段10>

这个就是封装了一下,没什么东东,接着这句scheduler.scheduleDirect(new SubscribeTask(parent)));我们知道这个scheduler是ObservableSubscribeOn的成员变量,通过上一篇的介绍,这个scheduler是NewThreadScheduler的对象

    @NonNull
    public Disposable scheduleDirect(@NonNull Runnable run) {
//run就是SubscribeTask 的对象嘛
        return scheduleDirect(run, 0L, TimeUnit.NANOSECONDS);
    }

                                                                              <源代码片段11>

返回个disposable,还要继续跟进

    @NonNull
    public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) {
        final Worker w = createWorker();//NewThreadScheduler的createWorker()方法创建NewThreadWorker对象

        final Runnable decoratedRun = RxJavaPlugins.onSchedule(run);//decoratedRun =run

        DisposeTask task = new DisposeTask(decoratedRun, w);

        w.schedule(task, delay, unit);

        return task;
    }

                                                                                      <源代码片段12>

DisposeTask这个类是什么呢

static final class DisposeTask implements Disposable, Runnable, SchedulerRunnableIntrospection {

.........................省略

   DisposeTask(@NonNull Runnable decoratedRun, @NonNull Worker w) {
            this.decoratedRun = decoratedRun;
            this.w = w;
        }

        @Override
        public void run() {
            runner = Thread.currentThread();
            try {
                decoratedRun.run();//decoratedRun是SubscribeTask的对象,是ObservableSubscribeOn的内部类
            } finally {
                dispose();
                runner = null;
            }
        }
......................省略
}

                                                                               <源代码片段13>

构建完之后,并没有直接返回,而是执行这段代码 w.schedule(task, delay, unit);w是NewThreadWorker的对象,那就跟踪这段代码吧

    @NonNull
    @Override
    public Disposable schedule(@NonNull final Runnable action, long delayTime, @NonNull TimeUnit unit) {
    /**
    *根据源码片段11、12、13得知一下
    *runnable是DisposeTask 它的run方法是调用SubscribeTask的run方法
    *delayTime=0L
    *unit为TimeUnit.NANOSECONDS
    */
        if (disposed) {//跳过
            return EmptyDisposable.INSTANCE;
        }
        return scheduleActual(action, delayTime, unit, null);
    }

                                                                    <源代码片段14>

那就是要继续scheduleActual方法

    @NonNull
    public ScheduledRunnable scheduleActual(final Runnable run, long delayTime, @NonNull TimeUnit unit, @Nullable DisposableContainer parent) {
        Runnable decoratedRun = RxJavaPlugins.onSchedule(run);//decoratedRun =run

        ScheduledRunnable sr = new ScheduledRunnable(decoratedRun, parent);

        if (parent != null) {//parent为null,跳过
            if (!parent.add(sr)) {
                return sr;
            }
        }

        Future f;
        try {
            if (delayTime <= 0) {//delayTime 此时为0
                f = executor.submit((Callable)sr);
            } else {
                f = executor.schedule((Callable)sr, delayTime, unit);
            }
            sr.setFuture(f);
        } catch (RejectedExecutionException ex) {
            if (parent != null) {
                parent.remove(sr);
            }
            RxJavaPlugins.onError(ex);
        }

        return sr;
    } 
  

                                                                         <源代码片段15>

ScheduledRunnable什么鬼,看看

public final class ScheduledRunnable extends AtomicReferenceArray
implements Runnable, Callable, Disposable {

......................省略

 public ScheduledRunnable(Runnable actual, DisposableContainer parent) {
        super(3);
        this.actual = actual;
        this.lazySet(0, parent);
    }

    @Override
    public Object call() {
        // Being Callable saves an allocation in ThreadPoolExecutor
        run();//call()最终还是调用run方法,并且返回null
        return null;
    }

    @Override
    public void run() {
        lazySet(THREAD_INDEX, Thread.currentThread());
        try {
            try {
                actual.run();
            } catch (Throwable e) {
                // Exceptions.throwIfFatal(e); nowhere to go
                RxJavaPlugins.onError(e);
            }
        } finally {
            lazySet(THREAD_INDEX, null);
            Object o = get(PARENT_INDEX);
            if (o != PARENT_DISPOSED && compareAndSet(PARENT_INDEX, o, DONE) && o != null) {
                ((DisposableContainer)o).delete(this);
            }

            for (;;) {
                o = get(FUTURE_INDEX);
                if (o == SYNC_DISPOSED || o == ASYNC_DISPOSED || compareAndSet(FUTURE_INDEX, o, DONE)) {
                    break;
                }
            }
        }
    }
......................省略
} 
  

                                                                                   <源代码片段16>

所以   <源代码片段15>执行 f = executor.submit((Callable)sr);executor好像是线程池,那就看看NewThreadWorker中的构造函数有这样的代码

    public NewThreadWorker(ThreadFactory threadFactory) {
        executor = SchedulerPoolFactory.create(threadFactory);
    }

                                                                                <源代码片段17>

NewThreadWorker是NewThreadScheduler的createWorker方法创建,threadFactory是个线程工厂。excutor的产生如下

 /**
     * Creates a ScheduledExecutorService with the given factory.
     * @param factory the thread factory
     * @return the ScheduledExecutorService
     */
    public static ScheduledExecutorService create(ThreadFactory factory) {
        final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1, factory);
        tryPutIntoPool(PURGE_ENABLED, exec);
        return exec;
    }

                                                                                <源代码片段18>

果然excutor是个线程池,那么 <源代码片段15> f = executor.submit((Callable)sr);这个方法不就是往里面加入一个ScheduledRunnable对象让线程池执行嘛。不知不觉中我们已经切换了线程,厉害啦!既然切换到线程,那就运行runable方法。

经过从ObservableSubscribeOn.SubscribeTask到最终的ScheduledRunnable,已经懵逼的朋友可以从 <源代码片段4>看,然后再看到这个位置就明白啦。引用关系图如下

rxJava和rxAndroid源码解析系列二之observer订阅_第1张图片

结合这上图,以及<源代码片段4>到  <源代码片段18>的运行,最终会调用ObservableSubscribeOn.SubscribeTask的run方法

里面又一句代码source.subscribe(parent);根据上篇的Observable的关系引用图可以知道source就是ObservableCreate对象阿。

就是这个继续订阅阿,发生在线程里面。Observable的subscribe实际执行的是subscribeActual嘛,那就看看ObservableCreate对这个方法的具体实现

 @Override
    protected void subscribeActual(Observer observer) {
        CreateEmitter parent = new CreateEmitter(observer);
        observer.onSubscribe(parent);

        try {
            source.subscribe(parent);
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            parent.onError(ex);
        }
    }

                                                                            <源代码片段19>

subscribeActual传入的对象就是ObservableSubscribeOn.SubscribeTask的parent,这个parent就是ObservableSubscribeOn的静态内部类对象SubscribeOnObserver,不清楚的朋友可以看一下关系引用图或者从头阅读这篇博客。先看一下这个类CreateEmitter

 static final class CreateEmitter
    extends AtomicReference
    implements ObservableEmitter, Disposable {

....................省略
        CreateEmitter(Observer observer) {
            this.observer = observer;
        }

....................省略
}

                                                                        <源代码片段20>

ObservableEmitter东西值得注意

public interface ObservableEmitter extends Emitter {
.....................省略
}

                                                                    <源代码片段21>

Emitter接口

public interface Emitter {

    /**
     * Signal a normal value.
     * @param value the value to signal, not null
     */
    void onNext(@NonNull T value);

    /**
     * Signal a Throwable exception.
     * @param error the Throwable to signal, not null
     */
    void onError(@NonNull Throwable error);

    /**
     * Signal a completion.
     */
    void onComplete();
}

                                                                             <源代码片段22>

Emitter接口比Observer 接口少一个方法void onSubscribe(@NonNull Disposable d);可以看出CreateEmitter对Observer进行了进一步装饰和扩展,<源代码片段19>中的observer.onSubscribe(parent);那就到SubscribeOnObserver里面看看了

   @Override
        public void onSubscribe(Disposable d) {
//构造的时候自动创建的this.upstream
            DisposableHelper.setOnce(this.upstream, d);
        }
    SubscribeOnObserver(Observer downstream) {
            this.downstream = downstream;
            this.upstream = new AtomicReference();
        }

                                                                            <源代码片段23>

那就是 DisposableHelper.setOnce(this.upstream, d);执行的情况啦

    public static boolean setOnce(AtomicReference field, Disposable d) {
        ObjectHelper.requireNonNull(d, "d is null");//判空操作
        if (!field.compareAndSet(null, d)) {//field的原子值肯定为null,所以if判断跳过
            d.dispose();
            if (field.get() != DISPOSED) {
                reportDisposableSet();
            }
            return false;
        }
        return true;//返回true
    }

                                                              <源代码片段24>

好吧,   <源代码片段19>中的代码 observer.onSubscribe(parent);结束,继续<源代码片段19>中的下一行代码source.subscribe(parent);这个source就是写一篇文章demo的时候Obserable.create(ObservableOnSubscribe)的参数嘛,就是自己实现的嘛,ObservableOnSubscribe就是demo自己写的东西嘛,也就是回调计划嘛。看到了吧,ObservableOnSubscribe的subscribe方法是执行在NewThreadWorker的线程池里面的一个线程中。

总结:Obserable的订阅就是不断地创建Observer嘛(装饰Observer),且是一个向最开始创建的Obserable传递Observer的过程。

当然涉及到了线程的切换,在这一篇不是核心,重点关注的是Observable的订阅,下一篇讲述子线程和主线程的切换。

有兴趣的朋友可以看看rxJava和rxAndroid源码解析系列三之线程切换

你可能感兴趣的:(android)