RxAndroid dispose实现原理

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhoujielunzhimi/article/details/90671417

示例如下:

    final Disposable disposable = Observable.create(new ObservableOnSubscribe<String>() {
        public void subscribe(@NonNull ObservableEmitter<String> e) {
            for (int i=0; i<100; i++) {
                if (e.isDisposed())
                    break;
                Thread.sleep(1000);
                e.onNext(String.valueOf(i));
            }
            e.onComplete();
        }
    }).map(new Function<Integer, String>() {
          public String apply(Integer number) {
            return number.toString();
          }
    }).subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe();
    new Handler().postDelayed(new Runnable() {
        public void run() {
            disposable.dispose();
        }
    }, 3000);

问题:

为什么调用disposable.dispose之后,ObservableEmitter.isDisposed为true?

分析:

经过调试发现,disposable.dispose这一句执行后最终会调用ObservableCreate.CreateEmitter.dispose。

【connect】在observer.onSubscribe时连接成一条线

  1. Disposable是什么?
  2. 怎样连接起来?
  3. 怎样跨越线程?
  4. 怎样跨越操作符?

1,Disposable是一个interface

/**
 * Represents a disposable resource.
 */
public interface Disposable {
    /**
     * Dispose the resource, the operation should be idempotent.
     */
    void dispose();

    /**
     * Returns true if this resource has been disposed.
     * @return true if this resource has been disposed
     */
    boolean isDisposed();
}

2,当subscribe调用后,会构造一个LambdaObserver,最终返回的Dispose就是这个。

@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError,
        Action onComplete, Consumer<? super Disposable> onSubscribe) {
    ObjectHelper.requireNonNull(onNext, "onNext is null");
    ObjectHelper.requireNonNull(onError, "onError is null");
    ObjectHelper.requireNonNull(onComplete, "onComplete is null");
    ObjectHelper.requireNonNull(onSubscribe, "onSubscribe is null");

    LambdaObserver<T> ls = new LambdaObserver<T>(onNext, onError, onComplete, onSubscribe);

    subscribe(ls);

    return ls;
}

假设只有Observable.create与subscribe,那么,将会进入ObservableCreate.subscribeActual

@Override
protected void subscribeActual(Observer<? super T> observer) {
    // observer即传入的LambdaObserver
    CreateEmitter<T> parent = new CreateEmitter<T>(observer);
    // 重点在此,看看里面做了什么
    observer.onSubscribe(parent);

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

LambdaObserver.onSubscribe

@Override
public void onSubscribe(Disposable d) {
    // 注意,继承了AtomicReference<Disposable>的类内部都有一个
    // volatile Disposable value,
    // 此处就是保存传入的Disposable(CreateEmitter),如此,
    // 当LambdaObserver的dispose调用时,会调用到CreateEmitter.dispose
    if (DisposableHelper.setOnce(this, d)) {
        try {
            onSubscribe.accept(this);
        } catch (Throwable ex) {
            Exceptions.throwIfFatal(ex);
            d.dispose();
            onError(ex);
        }
    }
}

3,先看subscribeOn,ObservableSubscribeOn

@Override
public void subscribeActual(final Observer<? super T> observer) {
    final SubscribeOnObserver<T> parent = new SubscribeOnObserver<T>(observer);
    // downstream保存SubscribeOnObserver对象(Disposable)
    observer.onSubscribe(parent);
    // 任务抛到线程,并且将其Disposable对象保存
    parent.setDisposable(scheduler.scheduleDirect(new SubscribeTask(parent)));
}

当source.subscribe调用后,SubscribeOnObserver内onSubscribe如下

@Override
public void onSubscribe(Disposable d) {
    // 将上游observable保存到upstream中
    DisposableHelper.setOnce(this.upstream, d);
}

当LambdaObserver.dispose调用后,SubscribeOnObserver内dispose被调用

@Override
public void dispose() {
    // 触发上游dispose
    DisposableHelper.dispose(upstream);
    // dispose任务,任务在线程中执行会先判断isDisposed再决定是否执行
    DisposableHelper.dispose(this);
}

再看observeOn,ObservableObserveOn

@Override
protected void subscribeActual(Observer<? super T> observer) {
    if (scheduler instanceof TrampolineScheduler) {
        source.subscribe(observer);
    } else {
        Scheduler.Worker w = scheduler.createWorker();
        // ObserveOnObserver.onNext时,会在worker中执行observer.onNext
        source.subscribe(new ObserveOnObserver<T>(observer, w, delayError, bufferSize));
    }
}

ObservableObserveOn.onSubscribe

@Override
public void onSubscribe(Disposable d) {
    if (DisposableHelper.validate(this.upstream, d)) {
        // 将CreateEmitter保存起来
        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;
                downstream.onSubscribe(this);
                schedule();
                return;
            }
            if (m == QueueDisposable.ASYNC) {
                sourceMode = m;
                queue = qd;
                downstream.onSubscribe(this);
                return;
            }
        }

        queue = new SpscLinkedArrayQueue<T>(bufferSize);
        // downstream保存此Disposable对象
        downstream.onSubscribe(this);
    }
}

LambdaObserver.dispose调用后,会执行ObservableObserveOn.dispose

@Override
public void dispose() {
    if (!disposed) {
        disposed = true;
        // 中止上游任务
        upstream.dispose();
        // 中止线程中的任务
        worker.dispose();
        if (getAndIncrement() == 0) {
            queue.clear();
        }
    }
}

 

4,以map为例

Observable.create().map().subscribe();

内部保存upstream,并把自己保存在downstream的Disposable对象中。

从map.subscribeActual开始

@Override
public void subscribeActual(Observer<? super U> t) {
    // source为ObservableCreate
    // t为LambdaObserver
    source.subscribe(new MapObserver<T, U>(t, function));
}

source.subscribe调用后会进入MapObserver.onSubscribe,在基类中BasicFuseableObserver

@Override
public final void onSubscribe(Disposable d) {
    // d为CreateEmitter,保存为upstream
    if (DisposableHelper.validate(this.upstream, d)) {
        this.upstream = d;
        if (d instanceof QueueDisposable) {
            this.qd = (QueueDisposable<T>)d;
        }
        if (beforeDownstream()) {
            // downstream为LambdaObserver,在构造函数中赋值的
            // 该句调用后,LambdaObserver保存此对象Disposable
            downstream.onSubscribe(this);

            afterDownstream();
        }
    }
}

因此,LambdaObserver.dispose调用后,会调用MapObserver.dispose

@Override
public void dispose() {
    // upstream即上面的CreateEmitter
    upstream.dispose();
}

总结:

下游会保存上游的Disposable对象,从而,在下游开始调用dispose后,实际上是去调用上游的dispose,如此,直到第一个Observable对象调用dispose停止,从而达到每个Disposable对象都为DISPOSED。

展开阅读全文

没有更多推荐了,返回首页