RxJava 是一个响应式编程框架,里面代码比较复杂,本系列文章将从以下几个角度来分析这个框架。
map、flatmap
。前面我们分析了 RxJava 的链路调用流程、常用的操作符 (map、flatmap
) 的逻辑、线程调度的原理,本文我们来实现一个简易版的 RxJava 框架。主要实现前面分析的 map、subscribeOn、observeOn
四个操作符的功能。
注: 代码已提交到 Github
版本:
Gradle 依赖:
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.19'
关联文章:
设计框架时会涉及到两个角色:事件源: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
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
实现几个线程调度器:
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;
}
}
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
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
Observable
对象。任务链创建流程
、逆向逐级订阅
、执行任务链流程
。Obserable.subscribe()
执行在对应的线程池中。