首页
登录 | 注册

RxJava1.x操作符初探之map

我们先来看看map操作符:

    Observable.just(1, 2, 3)
        .map(object : Func1<Int, String> {
             override fun call(t: Int?): String {
                return t.toString()
            }
        })

总结

map主要就是把最初的Subscriber1转化成MapSubscriber,交给Observable1,即OnSubscribe1处理
MapSubscriber,这时候MapSubscriber内部会先调用Map的参数Func来转换类型,最后再交给Subscriber1

那来看看map到底执行了什么吧:

Observable.java:

    public final <R> Observable<R> map(Func1<? super T, ? extends R> func) {
    //新建了一个Observable2,同时OnSubscribe2为OnSubscribeMap
        return create(new OnSubscribeMap<T, R>(this, func));
    }
    
    
OnSubscribeMap.java:

    public OnSubscribeMap(Observable<T> source, Func1<? super T, ? extends R> transformer) {
    //这个是Observable1
        this.source = source;
        this.transformer = transformer;
    }
    
    public void call(final Subscriber<? super R> o) {
    //重新封装Subscriber成MapSubscriber
        MapSubscriber<T, R> parent = new MapSubscriber<T, R>(o, transformer);
        o.add(parent);
        //执行MapSubscriber的onNext方法
        source.unsafeSubscribe(parent);
    }

MapSubscriber.java:

        public MapSubscriber(Subscriber<? super R> actual, Func1<? super T, ? extends R> mapper) {
         //actual是最初的Subscriber1
            this.actual = actual;
            //mapper就是map后面的Func1参数
            this.mapper = mapper;
        }

        @Override
        public void onNext(T t) {
            R result;
            try {
                //这步主要是为了转换类型
                result = mapper.call(t);
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                unsubscribe();
                onError(OnErrorThrowable.addValueAsLastCause(ex, t));
                return;
            }
            
            actual.onNext(result);
        }

最后来看看整个过程的流程图吧:

graph RL
    subgraph Observable
    Observable1-->Observable1.create{create}
    OnSubscribe1((OnSubscribe1))
    end
    
    subgraph ObservableMap
    Observable2
    OnSubscribe2((OnSubscribe2))
    end
    
    Observable1.create-->Observable2
    Subscriber1-->OnSubscribe2
    
    subgraph Subscriber
    MapSubscriber
    MapSubscriber.onNext{onNext}
    end
    
    subgraph Subscriber
    Subscriber1
    Subscriber1.onNext{onNext}
    end
 
 OnSubscribe2-->MapSubscriber
 MapSubscriber-->Observable1
 Observable1-->OnSubscribe1
 OnSubscribe1-->OnSubscribe1.call{call}
 OnSubscribe1.call-->MapSubscriber.onNext
     subgraph Func
     func1
     func1.call{call}
     end
     
     MapSubscriber.onNext-->func1.call
     func1.call-->Subscriber1.onNext

流程图:
RxJava1.x操作符初探之map



2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.008 s.
京ICP备10005923号