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);

}

完。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值