走进RxJava源码(二) -- 操作符Map

前言

        Observable.just("1", "2")
                .map(new Function() {
                    @Override
                    public String apply(String s) throws Exception {
                        return s;
                    }
                })
                .subscribe();

无论是just还是map,返回的都是Observable对象,其实这和设计模式中构造器模式很像,另外虽然上面每一步返回的是Observable,但是实际返回都是Observable实现类,每执行一步操作进行包装增强,这也算是代理模式的一种应用吧。

Map操作符

    public final  Observable map(Function mapper) {
        ObjectHelper.requireNonNull(mapper, "mapper is null");
        return RxJavaPlugins.onAssembly(new ObservableMap(this, mapper));
    }

new ObservableMap(this, mapper))中传入上一步Observable.just作为第一个参数,mapper是一个Function,这里返回的是Observable,这里可以验证之前的说法,每执行一步操作都是包装增强。

/**
 * A functional interface that takes a value and returns another value, possibly with a
 * different type and allows throwing a checked exception.
 *
 * @param  the input value type
 * @param  the output value type
 */
public interface Function {
    /**
     * Apply some calculation to the input value and return some other value.
     * @param t the input value
     * @return the output value
     * @throws Exception on error
     */
    R apply(@NonNull T t) throws Exception;
}

Function是转换的回调,用于确定如何转换,泛型T是转换前的类型,R是转换后的类型。

订阅

从上一章的分析可以知道调用subscribe()方法最终回调到ObservableMapsubscribeActual方法中。

public final class ObservableMap extends AbstractObservableWithUpstream {
    final Function function;

    public ObservableMap(ObservableSource source, Function function) {
        super(source);
        this.function = function;
    }

    @Override
    public void subscribeActual(Observer t) {
        source.subscribe(new MapObserver(t, function));
    }
    ......
}

ObservableMap中的source就是Observable.just,在subscribeActual就可以看到,它执行Observable.justsubscribe,这将会回调Observable.justsubscribeActual方法。
从这里可以猜到,Map在我们真正的下游前,执行了一个包装增强(这里是MapObserver),从而在下游获得到我们想要的数据形式。

接下来回顾ObservableFromArray一下subscribeActual的方法

public final class ObservableFromArray extends Observable {
    final T[] array;
    public ObservableFromArray(T[] array) {
        this.array = array;
    }

    @Override
    public void subscribeActual(Observer observer) {
        FromArrayDisposable d = new FromArrayDisposable(observer, array);

        observer.onSubscribe(d);

        if (d.fusionMode) {
            return;
        }

        d.run();
    }

    static final class FromArrayDisposable extends BasicQueueDisposable {

        final Observer downstream;

        final T[] array;

        int index;

        boolean fusionMode;

        volatile boolean disposed;

        FromArrayDisposable(Observer actual, T[] array) {
            this.downstream = actual;
            this.array = array;
        }

        ......

        @Override
        public boolean isEmpty() {
            return index == array.length;
        }

        @Override
        public void clear() {
            index = array.length;
        }

        @Override
        public void dispose() {
            disposed = true;
        }

        @Override
        public boolean isDisposed() {
            return disposed;
        }

        void run() {
            T[] a = array;
            int n = a.length;

            for (int i = 0; i < n && !isDisposed(); i++) {
                T value = a[i];
                if (value == null) {
                    downstream.onError(new NullPointerException("The " + i + "th element is null"));
                    return;
                }
                downstream.onNext(value);
            }
            if (!isDisposed()) {
                downstream.onComplete();
            }
        }
    }
}

在上一章中,下游直接就是我们的observer,而经过map操作后source.subscribe(new MapObserver(t, function));是经过MapObserver才到我们的observerObservableFromArray就操作的下游就是MapObserverObservableFromArray调用downstream.onNext(value);会回调到MapObserveronNext。到这里,可以猜到map操作就是在MapObserveronNext进行变换。

 static final class MapObserver extends BasicFuseableObserver {
        final Function mapper;

        MapObserver(Observer actual, Function mapper) {
            super(actual);
            this.mapper = mapper;
        }

        @Override
        public void onNext(T t) {
            if (done) {
                return;
            }

            if (sourceMode != NONE) {
                downstream.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;
            }
            downstream.onNext(v);
        }
    }

看到MapObserveronNext,对于map操作已经了然于胸了。其中最关键就是下面这一段。

            U v;

            try {
                v = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper function returned a null value.");
            } catch (Throwable ex) {
                fail(ex);
                return;
            }
            downstream.onNext(v);

在这里downstream就是我们真正的Observer了。你可以在GitHub找到我仿照RxJava流程写的伪代码。

你可能感兴趣的:(走进RxJava源码(二) -- 操作符Map)