美文网首页
rxjava笔记(2)

rxjava笔记(2)

作者: preCh | 来源:发表于2016-12-17 22:05 被阅读30次

    rxjava笔记(2)

    map与flatMap的原理

    map的原理,可以查看map的源码进行分析。
    会发现map()其实调用了left方法
    left的源码大致过程为:

    return new Observable<R>(new OnSubscribe<R>() {
               @Override
               public void call(Subscriber<? super R> o) {
                   try {
                       Subscriber<? super T> st = hook.onLift(operator).call(o);
                       try {
                           st.onStart();
                           onSubscribe.call(st);
                       } catch (Throwable e) {
                           if (e instanceof OnErrorNotImplementedException) {
                               throw (OnErrorNotImplementedException) e;
                           }
                           st.onError(e);
                       }
                   } catch (Throwable e) {
                       if (e instanceof OnErrorNotImplementedException) {
                           throw (OnErrorNotImplementedException) e;
                       }
                       o.onError(e);
                   }
               }
           });
    

    可以看到,在left方法中,返回了一个新建的Observable对象
    接下来具体分析可以看出:

    • left中生成了一个新的泛型为R的Observable对象
    • left后继续调用subscribe的时候,使用的OnSubscriber是新的Observable的onSubscribe对象
    • 新observable对象中的call回调中会执行onSubscribe对象的call方法,这个onSubscribe对象是老的Observable对象中的成员变量
    • rxjava的left方法利用上述实现了事件流中的对象的变换。非常的巧妙。将新的Subscriber和原始的Observable带来发布-订阅关系。思想有点类似于代理。

    同理,flatMap于map的原理差不多,只是变换成了一个Observable对象

    相关文章

      网友评论

          本文标题:rxjava笔记(2)

          本文链接:https://www.haomeiwen.com/subject/sframttx.html