阅读 40

【RxJava】observeOn源码解析

小栗子

Observable.just(1)
        .observeOn(Schedulers.newThread())
        .subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                // 1
            }

            @Override
            public void onNext(@NonNull Integer integer) {
                // 2
            }

            @Override
            public void onError(@NonNull Throwable e) {
                // 3
            }

            @Override
            public void onComplete() {
                // 4
            }
        });
复制代码

observeOn

observeOn原型如下

public final Observable<T> observeOn(Scheduler scheduler) {
    return observeOn(scheduler, false, bufferSize());
}

public final Observable<T> observeOn(Scheduler scheduler, boolean delayError, int bufferSize) {
    ObjectHelper.requireNonNull(scheduler, "scheduler is null");
    ObjectHelper.verifyPositive(bufferSize, "bufferSize");
    return RxJavaPlugins.onAssembly(new ObservableObserveOn<T>(this, scheduler, delayError, bufferSize));
}
复制代码

observeOn返回一个ObservableObserveOn对象

ObserveOnObserver#subscribe

public final void subscribe(Observer<? super T> observer) {
    ...
    subscribeActual(observer);
    ...
}
复制代码

subscribe方法调用ObservableObserveOn的subscribeActual方法

ObserveOnObserver#subscribeActual

@Override
protected void subscribeActual(Observer<? super T> observer) {
    if (scheduler instanceof TrampolineScheduler) {
        source.subscribe(observer);
    } else {
        // 1
        Scheduler.Worker w = scheduler.createWorker();
        // 2
        source.subscribe(new ObserveOnObserver<T>(observer, w, delayError, bufferSize));
    }
}
复制代码

注释1处使用scheduler的createWorker方法创建一个Scheduler.Worker,以后说。

注释2进行了订阅,且未发生线程切换。

ObservableJust#subscribeActual

protected void subscribeActual(Observer<? super T> observer) {
    ScalarDisposable<T> sd = new ScalarDisposable<T>(observer, value);
    observer.onSubscribe(sd);
    sd.run();
}
复制代码

subscribeActual调用onSubscribe方法。

ObserveOnObserver#onSubscribe

@Override
public void onSubscribe(Disposable d) {
    if (DisposableHelper.validate(this.upstream, d)) {
        this.upstream = d;
        if (d instanceof QueueDisposable) {
            @SuppressWarnings("unchecked")
            QueueDisposable<T> qd = (QueueDisposable<T>) d;

            int m = qd.requestFusion(QueueDisposable.ANY | QueueDisposable.BOUNDARY);
           
            if (m == QueueDisposable.SYNC) {
                sourceMode = m;
                queue = qd;
                done = true;
                // 1
                downstream.onSubscribe(this);
                schedule();
                return;
            }
            if (m == QueueDisposable.ASYNC) {
                sourceMode = m;
                queue = qd;
                // 2
                downstream.onSubscribe(this);
                return;
            }
        }

        queue = new SpscLinkedArrayQueue<T>(bufferSize);
        // 3
        downstream.onSubscribe(this);
    }
}
复制代码

注释123处在调用onSubscribe方法时均未发生线程切换。

注:在我们的例子中走的是注释1处的代码。

ObserveOnObserver#schedule

void schedule() {
    if (getAndIncrement() == 0) {
        worker.schedule(this);
    }
}

@Override
public void run() {
    if (outputFused) {
        drainFused();
    } else {
        drainNormal();
    }
}
复制代码

调度后,执行run方法.

ObserveOnObserver#drainNormal

void drainNormal() {
    int missed = 1;

    final SimpleQueue<T> q = queue;
    final Observer<? super T> a = downstream;

    for (;;) {
        if (checkTerminated(done, q.isEmpty(), a)) {
            return;
        }

        for (;;) {
            boolean d = done;
            T v;

            try {
                v = q.poll();
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                disposed = true;
                upstream.dispose();
                q.clear();
                a.onError(ex);
                worker.dispose();
                return;
            }
            boolean empty = v == null;

            if (checkTerminated(d, empty, a)) {
                return;
            }

            if (empty) {
                break;
            }

            // 1
            a.onNext(v);
        }

        missed = addAndGet(-missed);
        if (missed == 0) {
            break;
        }
    }
}
复制代码

注释1处调用了onNext

ObserveOnObserver#checkTerminated

boolean checkTerminated(boolean d, boolean empty, Observer<? super T> a) {
    if (disposed) {
        queue.clear();
        return true;
    }
    if (d) {
        Throwable e = error;
        if (delayError) {
            if (empty) {
                disposed = true;
                if (e != null) {
                    a.onError(e);
                } else {
                    a.onComplete();
                }
                worker.dispose();
                return true;
            }
        } else {
            if (e != null) {
                disposed = true;
                queue.clear();
                a.onError(e);
                worker.dispose();
                return true;
            } else
            if (empty) {
                disposed = true;
                // 1
                a.onComplete();
                worker.dispose();
                return true;
            }
        }
    }
    return false;
}
复制代码

注释1处调用了onComplete

文章分类
Android
文章标签