ObservableMap調用流程分析

代碼一:

 observable.subscribeOn(Schedulers.io())

        .map(new ResultFunc<Observable>())

        .observeOn(AndroidSchedulers.mainThread())

        .subscribe(spSubscriber);

 

map會調用以下方法,mapper參數就是new ResultFunc<Observable>(),RxJavaPlugins.onAssembly(new ObservableMap<T, R>(this, mapper))這句話中的this,就是代碼一中的observablesubscribeOn,

代碼二 :

@CheckReturnValue

@SchedulerSupport(SchedulerSupport.NONE)

public final <R> Observable<R> map(Function<? super T, ? extends R> mapper) {

    ObjectHelper.requireNonNull(mapper, "mapper is null");

    return RxJavaPlugins.onAssembly(new ObservableMap<T, R>(this, mapper));

}

把this,對象保存爲source,並註冊了function函數

代碼三:

public ObservableMap(ObservableSource<T> source, Function<? super T, ? extends U> function) {

    super(source);

    this.function = function;

}

然後執行代碼一中的subscribe方法,進行觀察者註冊,

代碼四:在subscribe方法中會調用subscribeActual(observer)方法,這個方法是父類的抽象方法,因爲當前的子類爲ObservableMap,所以會去調用

代碼五

@SchedulerSupport(SchedulerSupport.NONE)

@Override

public final void subscribe(Observer<? super T> observer) {

    ObjectHelper.requireNonNull(observer, "observer is null");

    try {

        observer = RxJavaPlugins.onSubscribe(this, observer);



        ObjectHelper.requireNonNull(observer, "Plugin returned null Observer");



        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;

    }

}

在代碼五中,source會去註冊source的subscribe,因爲代碼四中的subscribe是ObservableMap的(這個地方有疑問),這個source就是代碼一中的observable,這樣子就把代碼五中包裝一層new MapObserver<T, U>(t, function)的又成功註冊給了source,當source發出onNext時,就會先觸發MapObserver的onNext

代碼五:

@Override

public void subscribeActual(Observer<? super U> t) {

    source.subscribe(new MapObserver<T, U>(t, function));

}

在MapObserver的onNext方法中會去調用轉換方法mapper.apply(t),並且把轉換後的結果v返回,最後在調用代碼一中的 spSubscriber方法,實現了結果調用。

代碼六:

@Override

public void onNext(T t) {

    if (done) {

        return;

    }



    if (sourceMode != NONE) {

        actual.onNext(null);

        return;

    }



    U v;



    try {

        v = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper function returned a null value.");

    } catch (Throwable ex) {

        fail(ex);

        return;

    }

    actual.onNext(v);

}

完。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章