RxJava(四) — 实现一个简易版的 RxJava 框架

实现一个简易版的 RxJava 框架

    • 一、概述
    • 二、框架的搭建
    • 三、map 操作符的实现
    • 四、调度器 (Scheduler) 的实现
    • 五、subscribeOn 操作符的实现
    • 六、observeOn 操作符的实现
    • 七、小结

一、概述

RxJava 是一个响应式编程框架,里面代码比较复杂,本系列文章将从以下几个角度来分析这个框架。

  1. RxJava 的链路调用流程。
  2. RxJava 的常用操作符 map、flatmap
  3. RxJava 的线程调度。
  4. 自己实现一个简易版的 RxJava 框架。

前面我们分析了 RxJava 的链路调用流程、常用的操作符 (map、flatmap) 的逻辑、线程调度的原理,本文我们来实现一个简易版的 RxJava 框架。主要实现前面分析的 map、subscribeOn、observeOn 四个操作符的功能。

注: 代码已提交到 Github


版本:

  • RxJava:Github传送门
  • RxAndroid:Github传送门

Gradle 依赖:

implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.19'

关联文章:

  1. RxJava(一) — 链路调用流程分析
  2. RxJava(二) — 常用操作符之 map & flatmap
  3. RxJava(三) — 线程调度
  4. RxJava(四) — 实现一个简易版的 RxJava 框架
  5. 设计模式 — 观察者模式
  6. RxJava 中文文档

二、框架的搭建

设计框架时会涉及到两个角色:事件源:Observable接收者:Observer

Observer

public interface Observer<T> {
    void onNext(T t);
    void onCompleted();
    void onError(Throwable t);
}

Observable

public abstract class Observable<T> {

    public static <T> Observable<T> create(OnSubscribe<T> onSubscribe) {
        return new ObservableCreate<T>(onSubscribe);
    }

	// 用于外部调用
    public void subscribe(Observer<? super T> observer) {
        subscribeActual(observer);
    }
	// 用于子类实现
    protected abstract void subscribeActual(Observer<? super T> observer);

    public interface OnSubscribe<T> {
        void subscribe(Observer<? super T> observer);
    }
}

ObservableCreate

public class ObservableCreate<T> extends Observable<T> {

    OnSubscribe source;
    public ObservableCreate(OnSubscribe<T> source) {
        this.source = source;
    }

    @Override
    protected void subscribeActual(Observer<? super T> observer) {
        CreateObserver<T> parent = new CreateObserver<>(observer);
        source.subscribe(parent);
    }

    static class CreateObserver<T> implements Observer<T> {

        Observer downStream;

        public CreateObserver(Observer<? super T> observer) {
            downStream = observer;
        }

        @Override
        public void onNext(T t) {
            downStream.onNext(t);
        }

        @Override
        public void onCompleted() {
            downStream.onCompleted();
        }

        @Override
        public void onError(Throwable t) {
            downStream.onError(t);
        }
    }
}

Client 调用示例:

private void clickNormal() {
Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void subscribe(Observer<? super String> observer) {
            observer.onNext("11");
            observer.onNext("22");
            observer.onNext("33");
            observer.onCompleted();
        }
    }).subscribe(this.<String>getObserver());
}

private <T> Observer<T> getObserver() {
    return new Observer<T>() {
        @Override
        public void onNext(T s) {
            Log.d(TAG, "onNext = " + s
                    + "; Type = " + s.getClass().getSimpleName()
                    + "; Current Thread = " + Thread.currentThread().getName());
        }

        @Override
        public void onCompleted() {
            Log.d(TAG, "onCompleted");
        }

        @Override
        public void onError(Throwable t) {}
    };
}

输出结果:

D/MainActivity: onNext = 11; Type = String; Current Thread = main
D/MainActivity: onNext = 22; Type = String; Current Thread = main
D/MainActivity: onNext = 33; Type = String; Current Thread = main
D/MainActivity: onCompleted


三、map 操作符的实现

Observable

新增一个操作符的调用方法。

public abstract class Observable<T> {
	// 新增一个操作符的调用方法。
    public <R> Observable<R> map(Function<? super T, ? extends R> mapper) {
        return (Observable<R>) new ObservableMap<T, R>(this, mapper);
    }
}

ObservableMap

新增一个 ObservableMap 处理 map 操作符的逻辑。

public class ObservableMap<T, R> extends Observable<T> {

    Observable<T> source;
    Function<? super T, ? extends R> mapper;

    public ObservableMap(Observable<T> source, Function<? super T, ? extends R> mapper) {
        this.source = source;
        this.mapper = mapper;
    }

    @Override
    protected void subscribeActual(Observer<? super T> observer) {
        MapObserver<T, R> parent = new MapObserver<>(observer, mapper);
        source.subscribe(parent);
    }

    static class MapObserver<T, R> implements Observer<T> {

        Observer downStream;
        Function<? super T, ? extends R> mapper;

        public MapObserver(Observer<? super T> observer, Function<? super T, ? extends R> mapper) {
            this.downStream = observer;
            this.mapper = mapper;
        }

        @Override
        public void onNext(T t) {
        	// 在onNext中执行类型转换的操作。
            R r = mapper.apply(t);
            downStream.onNext(r);
        }

        @Override
        public void onCompleted() {
            downStream.onCompleted();
        }

        @Override
        public void onError(Throwable t) {
            downStream.onError(t);
        }
    }
}

Client 调用示例:

private void clickMap() {
    Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void subscribe(Observer<? super String> observer) {
            observer.onNext("11");
            observer.onNext("22");
            observer.onNext("33");
            observer.onCompleted();
        }
    }).map(new Function<String, Integer>() {
        @Override
        public Integer apply(String s) {
            return Integer.parseInt(s);
        }
    }).subscribe(this.<Integer>getObserver());
}

输出结果:

D/MainActivity: onNext = 11; Type = Integer; Current Thread = main
D/MainActivity: onNext = 22; Type = Integer; Current Thread = main
D/MainActivity: onNext = 33; Type = Integer; Current Thread = main
D/MainActivity: onCompleted


四、调度器 (Scheduler) 的实现

在实现线程切换功能前我们需要实现几个线程调度器。

Scheduler

实现几个线程调度器:IOScheduler、NewThreadScheduler、MainScheduler

public interface Scheduler {
    void schedule(Runnable runnable);
}

public class IOScheduler implements Scheduler {
    ExecutorService service;

    public IOScheduler() {
    	// RxThreadFactory 线程工程
        service = Executors.newCachedThreadPool(new RxThreadFactory("-thread-io-"));
    }

    @Override
    public void schedule(Runnable runnable) {
        service.submit(runnable);
    }
}

public class NewThreadScheduler implements Scheduler {
    ExecutorService service;

    public NewThreadScheduler() {
        service = Executors.newCachedThreadPool(new RxThreadFactory("-thread-new-"));
    }

    @Override
    public void schedule(Runnable runnable) {
        service.submit(runnable);
    }
}


public class MainScheduler implements Scheduler {
    private Handler mMainHandler;

    public MainScheduler() {
        mMainHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void schedule(Runnable runnable) {
        ScheduledRunnable scheduled = new ScheduledRunnable(runnable);
        Message message = Message.obtain(mMainHandler, scheduled);
        mMainHandler.sendMessageDelayed(message, 0);
    }

    private static final class ScheduledRunnable implements Runnable {
        private final Runnable delegate;

        ScheduledRunnable(Runnable delegate) {
            this.delegate = delegate;
        }

        @Override
        public void run() {
            delegate.run();
        }
    }
}

Schedulers 调度器的管理类

public class Schedulers {

    static final Scheduler IO;
    static final Scheduler MAIN;
    static final Scheduler NEW_THREAD;

    static {
        IO = new IOScheduler();
        MAIN = new MainScheduler();
        NEW_THREAD = new NewThreadScheduler();
    }

    public static Scheduler io() {
        return IO;
    }

    public static Scheduler mainThread() {
        return MAIN;
    }

    public static Scheduler newThread() {
        return NEW_THREAD;
    }
}

五、subscribeOn 操作符的实现

public class ObservableSubscribeOn<T> extends Observable<T> {

    Observable<T> source;
    Scheduler scheduler;

    public ObservableSubscribeOn(Observable<T> source, Scheduler scheduler) {
        this.source = source;
        this.scheduler = scheduler;
    }

    @Override
    protected void subscribeActual(Observer<? super T> observer) {
        SubscribeOnObserver parent = new SubscribeOnObserver<>(observer);
        // 将Obserable.subscribe()操作放到Runnable中执行。
        scheduler.schedule(new SubscribeTask(parent));
    }

    static class SubscribeOnObserver<T> implements Observer<T> {

        Observer downStream;

        public SubscribeOnObserver(Observer<? super T> observer) {
            this.downStream = observer;
        }

        @Override
        public void onNext(T t) {
            downStream.onNext(t);
        }

        @Override
        public void onCompleted() {
            downStream.onCompleted();
        }

        @Override
        public void onError(Throwable t) {
            downStream.onError(t);
        }
    }


    final class SubscribeTask implements Runnable {

        private final SubscribeOnObserver<T> parent;

        SubscribeTask(SubscribeOnObserver<T> parent) {
            this.parent = parent;
        }

        @Override
        public void run() {
            source.subscribe(parent);
        }
    }
}

Client 调用示例:

private void clickSubscribeOn() {
    Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void subscribe(Observer<? super String> observer) {
            observer.onNext("11");
            observer.onNext("22");
            observer.onNext("33");
            observer.onCompleted();
        }
    }).map(new Function<String, Integer>() {
        @Override
        public Integer apply(String s) {
            Log.d(TAG, "map.apply 所在线程 = " + Thread.currentThread().getName());
            return Integer.parseInt(s);
        }
    }).subscribeOn(Schedulers.newThread())
    .subscribe(this.<Integer>getObserver());
}

输出结果:

D/MainActivity: map.apply 所在线程 = -thread-new-
D/MainActivity: onNext = 11; Type = Integer; Current Thread = -thread-new-
D/MainActivity: map.apply 所在线程 = -thread-new-
D/MainActivity: onNext = 22; Type = Integer; Current Thread = -thread-new-
D/MainActivity: map.apply 所在线程 = -thread-new-
D/MainActivity: onNext = 33; Type = Integer; Current Thread = -thread-new-
D/MainActivity: onCompleted


六、observeOn 操作符的实现

ObservableObserveOn

public class ObservableObserveOn<T> extends Observable<T> {

    Observable<T> source;
    Scheduler scheduler;

    public ObservableObserveOn(Observable<T> source, Scheduler scheduler) {
        this.source = source;
        this.scheduler = scheduler;
    }

    @Override
    protected void subscribeActual(Observer<? super T> observer) {
        source.subscribe(new ObserveOnObserver<T>(scheduler, observer));
    }

    static final class ObserveOnObserver<T> implements Observer<T>, Runnable {

        Scheduler scheduler;
        Observer downStream;
        T value;

        public ObserveOnObserver(Scheduler scheduler, Observer<? super T> observer) {
            this.scheduler = scheduler;
            this.downStream = observer;
        }

        @Override
        public void onNext(T t) {
            value = t;
            // 通过调度器切换线程。
            scheduler.schedule(this);
        }

        @Override
        public void onCompleted() {
            downStream.onCompleted();
        }

        @Override
        public void onError(Throwable t) {
            downStream.onError(t);
        }

        @Override
        public void run() {
            downStream.onNext(value);
        }
    }
}

Client 调用示例:

private void clickObserveOn() {
    Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void subscribe(Observer<? super String> observer) {
            observer.onNext("11");
            observer.onNext("22");
            observer.onNext("33");
            observer.onCompleted();
        }
    }).map(new Function<String, Integer>() {
        @Override
        public Integer apply(String s) {
            Log.d(TAG, "map.apply 所在线程 = " + Thread.currentThread().getName());
            return Integer.parseInt(s);
        }
    }).subscribeOn(Schedulers.newThread())
    .observeOn(Schedulers.mainThread())
    .subscribe(this.<Integer>getObserver());
}

输出结果:

D/MainActivity: map.apply 所在线程 = -thread-new-
D/MainActivity: map.apply 所在线程 = -thread-new-
D/MainActivity: map.apply 所在线程 = -thread-new-
D/MainActivity: onCompleted
D/MainActivity: onNext = 11; Type = Integer; Current Thread = main
D/MainActivity: onNext = 33; Type = Integer; Current Thread = main
D/MainActivity: onNext = 33; Type = Integer; Current Thread = main


七、小结

  1. 每个操作符都会生成一个新的 Observable 对象。
  2. RxJava 调用链的串联分为三个流程:
    1. 任务链创建流程
    2. 逆向逐级订阅
    3. 执行任务链流程
  3. 线程的切换分为两种:
    1. 切换到主线程需要使用 Handler 进行线程切换。
    2. 切换到其他线程的,只需要将订阅逻辑 Obserable.subscribe() 执行在对应的线程池中。

你可能感兴趣的:(开源框架源码分析)