1.使用
举个例子:
Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
emitter.onNext("1");
}
})
.subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer integer) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
例子很简单,先是创建一个被观察者,然后在订阅观察者。具体怎么订阅的看一下源码就知道。
2.解析
先是创建被观察者:
- create:
@CheckReturnValue
@NonNull
@SchedulerSupport(SchedulerSupport.NONE)
public static Observable create(ObservableOnSubscribe source) {
ObjectHelper.requireNonNull(source, "source is null");
return RxJavaPlugins.onAssembly(new ObservableCreate(source));//将ObservableCreate转换为Observable
}
可以看到,先是生成ObservableCreate对象后又转换为了Observable对象。至于 RxJavaPlugins.onAssembly执行了什么,可以大概看一下:
static volatile Function super Observable, ? extends Observable> onObservableAssembly;
@SuppressWarnings({ "rawtypes", "unchecked" })
@NonNull
public static Observable onAssembly(@NonNull Observable source) {
Function super Observable, ? extends Observable> f = onObservableAssembly;
//这里f——onObservableAssembly为null,因为是静态方法调用的,为执行过赋值所以为空
if (f != null) {
return apply(f, source);
}
return source;
}
所以结果很明显,在当前情况下,就只是执行了一个将结果转换为Observable而已(返回值转换)。
所以,第一步我们就得到了一个真实值为ObservableCreate的Observable对象。
接着是订阅:
- subscribe
@SchedulerSupport(SchedulerSupport.NONE)
@Override
public final void subscribe(Observer super T> observer) {
ObjectHelper.requireNonNull(observer, "observer is null");
try {
observer = RxJavaPlugins.onSubscribe(this, observer);//跟刚才一样,也是只是执行类型转换
ObjectHelper.requireNonNull(observer, "The RxJavaPlugins.onSubscribe hook returned a null Observer. Please change the handler provided to RxJavaPlugins.setOnObservableSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins");
//抽象方法,在其子类中执行
subscribeActual(observer);
} catch (NullPointerException e) { // NOPMD
throw e;
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
// can't call onError because no way to know if a Disposable has been set or not
// can't call onSubscribe because the call might have set a Subscription already
RxJavaPlugins.onError(e);
NullPointerException npe = new NullPointerException("Actually not, but can't throw other exceptions due to RS");
npe.initCause(e);
throw npe;
}
}
protected abstract void subscribeActual(Observer super T> observer);
由第一步可知,subscribeActual具体执行是在ObservableCreate类之中。
@Override
protected void subscribeActual(Observer super T> observer) {
CreateEmitter parent = new CreateEmitter(observer);//根据observer创建适配器
observer.onSubscribe(parent);//调用观察者observer的onSubscribe
try {
source.subscribe(parent);//之后才调用被观察者的subscribe方法
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
parent.onError(ex);
}
}
为便于观看,这里将subscribeActual和CreateEmitter的代码分开来写了:
static final class CreateEmitter
extends AtomicReference
implements ObservableEmitter, Disposable {
private static final long serialVersionUID = -3434801548987643227L;
final Observer super T> observer;
CreateEmitter(Observer super T> observer) {
this.observer = observer;//缓存
}
@Override
public void onNext(T t) {
if (t == null) {
onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
return;
}
//如果已经执行了disposed了,就不再执行(使用我们通过设置disposed来控制是否接着往下执行onComplete、onError等这些观察者的方法
if (!isDisposed()) {
observer.onNext(t);
}
}
@Override
public void onError(Throwable t) {
if (!tryOnError(t)) {
RxJavaPlugins.onError(t);
}
}
@Override
public boolean tryOnError(Throwable t) {
if (t == null) {
t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
}
if (!isDisposed()) {
try {
observer.onError(t);
} finally {
dispose();//一定会执行到
}
return true;
}
return false;
}
@Override
public void onComplete() {
if (!isDisposed()) {
try {
observer.onComplete();
} finally {
dispose();//一定会执行到
}
}
}
@Override
public void setDisposable(Disposable d) {
DisposableHelper.set(this, d);
}
@Override
public void setCancellable(Cancellable c) {
setDisposable(new CancellableDisposable(c));
}
@Override
public ObservableEmitter serialize() {
return new SerializedEmitter(this);
}
@Override
public void dispose() {
DisposableHelper.dispose(this);
}
@Override
public boolean isDisposed() {
return DisposableHelper.isDisposed(get());
}
@Override
public String toString() {
return String.format("%s{%s}", getClass().getSimpleName(), super.toString());
}
}
可以看到,CreateEmitter实现了Disposable,所以是个Disposable,同时实现了ObservableEmitter接口以至于实现其接口方法。
这里适配器的作用就是将observer封装,然后间接调用它实现的这些方法。
必须重点指出的是,订阅的方法是先执行observer的onSubscribe方法后执行source的subscribe方法,这就是为什么要订阅后Observable才会发送数据,这是观察者模式的一种灵活实现!值得学习。
以上就是rxjava从创建到订阅的大致流程,附上流程图:
3.高级应用
刚才分析了rxjava从创建到订阅的流程,接下来重点介绍下他的其他高级应用。比如map和flatMap、timer等方法。其实现方法类似,比如timer:
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
public static Observable timer(long delay, TimeUnit unit, Scheduler scheduler) {
ObjectHelper.requireNonNull(unit, "unit is null");
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
return RxJavaPlugins.onAssembly(new ObservableTimer(Math.max(delay, 0L), unit, scheduler));
}
是不是似曾相识?没错,就更create方法类似,所以ObservableTimer里面究竟干了什么,相信你已经猜到了,不信你看:
public ObservableTimer(long delay, TimeUnit unit, Scheduler scheduler) {
this.delay = delay;
this.unit = unit;
this.scheduler = scheduler;
}
构造方法保存传递过来的参数,那接下来是不是有subscribeActual?没错,确实有:
@Override
public void subscribeActual(Observer super Long> observer) {
TimerObserver ios = new TimerObserver(observer);//创建封装observer的适配器
observer.onSubscribe(ios);//先调用observer的onSubscribe
Disposable d = scheduler.scheduleDirect(ios, delay, unit);
ios.setResource(d);//后调用上游的方法
}
而且这里也是对Observer进行了封装:
static final class TimerObserver extends AtomicReference
implements Disposable, Runnable {
private static final long serialVersionUID = -2809475196591179431L;
final Observer super Long> downstream;
TimerObserver(Observer super Long> downstream) {
this.downstream = downstream;
}
@Override
public void dispose() {
DisposableHelper.dispose(this);
}
@Override
public boolean isDisposed() {
return get() == DisposableHelper.DISPOSED;
}
@Override
public void run() {
if (!isDisposed()) {
downstream.onNext(0L);
lazySet(EmptyDisposable.INSTANCE);
downstream.onComplete();
}
}
public void setResource(Disposable d) {
DisposableHelper.trySet(this, d);
}
}
方法与CreateEmitter类似,参照CreateEmitter。
再来看看Map,也是一样:
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final Observable map(Function super T, ? extends R> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new ObservableMap(this, mapper));
}
类似,干脆直接贴代码算了>_<
public ObservableMap(ObservableSource source, Function super T, ? extends U> function) {
super(source);
this.function = function;
}
构造方法缓存传递过来的参数,这里是Observable和function,
然后就是subscribeActual(通过前面的分析,我们知道当订阅发生时调用抽象方法subscribeActual实际上调用的对应的实际Observable的subscribeActual):
@Override
public void subscribeActual(Observer super U> t) {
source.subscribe(new MapObserver(t, function));
}
static final class MapObserver extends BasicFuseableObserver {
final Function super T, ? extends U> mapper;
MapObserver(Observer super U> actual, Function super T, ? extends U> 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 {
//apply(t)方法就是我们自己实现了的那个方法
v = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper function returned a null value.");
} catch (Throwable ex) {
fail(ex);
return;
}
downstream.onNext(v);
}
@Override
public int requestFusion(int mode) {
return transitiveBoundaryFusion(mode);
}
@Nullable
@Override
public U poll() throws Exception {
T t = qd.poll();
return t != null ? ObjectHelper.requireNonNull(mapper.apply(t), "The mapper function returned a null value.") : null;
}
}
操作符的源码都差不多,如果继续对操作符源码进行分析就有点无聊了。所以接下来还是重点讲解下rxjava的线程调度方面的知识。
4.线程调度
先把本章的例子完整给出来:
Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(ObservableEmitter emitter) throws Exception {
emitter.onNext("1");
}
}).map(new Function() {
@Override
public Integer apply(String s) throws Exception {
return Integer.parseInt(s);
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Integer integer) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
这里重点讲解observeOn和subscribeOn。
(1)observeOn
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Observable observeOn(Scheduler scheduler) {
return observeOn(scheduler, false, bufferSize());//初始化,即传递进来的AndroidSchedulers.mainThread()
}
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Observable observeOn(Scheduler scheduler, boolean delayError, int bufferSize) {
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
ObjectHelper.verifyPositive(bufferSize, "bufferSize");
return RxJavaPlugins.onAssembly(new ObservableObserveOn(this, scheduler, delayError, bufferSize));//呵呵,还是它
}
好,我们忍住想打他的冲动,接着往下看:
public ObservableObserveOn(ObservableSource source, Scheduler scheduler, boolean delayError, int bufferSize) {
super(source);
this.scheduler = scheduler;
this.delayError = delayError;
this.bufferSize = bufferSize;
}
不用说,接下来就是subscribeActual了:
@Override
protected void subscribeActual(Observer super T> observer) {
if (scheduler instanceof TrampolineScheduler) {
source.subscribe(observer);
} else {
Scheduler.Worker w = scheduler.createWorker();//从传递过来的线程中创建出worker
source.subscribe(new ObserveOnObserver(observer, w, delayError, bufferSize));//调用Observer的subscribe,订阅
}
}
ObserveOnObser,又是封装:
static final class ObserveOnObserver extends BasicIntQueueDisposable
implements Observer, Runnable {
private static final long serialVersionUID = 6576896619930983584L;
final Observer super T> downstream;
final Scheduler.Worker worker;
final boolean delayError;
final int bufferSize;
SimpleQueue queue;
Disposable upstream;
Throwable error;
volatile boolean done;
volatile boolean disposed;
int sourceMode;
boolean outputFused;
ObserveOnObserver(Observer super T> actual, Scheduler.Worker worker, boolean delayError, int bufferSize) {
//初始化参数,赋值
this.downstream = actual;
this.worker = worker;
this.delayError = delayError;
this.bufferSize = bufferSize;
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
if (d instanceof QueueDisposable) {
@SuppressWarnings("unchecked")
QueueDisposable qd = (QueueDisposable) d;
int m = qd.requestFusion(QueueDisposable.ANY | QueueDisposable.BOUNDARY);
if (m == QueueDisposable.SYNC) {
sourceMode = m;
queue = qd;
done = true;
downstream.onSubscribe(this);
schedule();
return;
}
if (m == QueueDisposable.ASYNC) {
sourceMode = m;
queue = qd;
downstream.onSubscribe(this);
return;
}
}
queue = new SpscLinkedArrayQueue(bufferSize);//创建一个队列,主要用于保存Observable发送过来的数据
downstream.onSubscribe(this);//先调用observer的onSubscribe
}
}
@Override
public void onNext(T t) {
if (done) {
return;
}
//如果不是异步的
if (sourceMode != QueueDisposable.ASYNC) {
queue.offer(t);//数据入队
}
schedule();//跳到worker的线程将queue里面的值发送给Observer
}
@Override
public void onError(Throwable t) {
if (done) {
RxJavaPlugins.onError(t);
return;
}
error = t;
done = true;
schedule();
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
schedule();
}
@Override
public void dispose() {
if (!disposed) {
disposed = true;
upstream.dispose();
worker.dispose();
if (getAndIncrement() == 0) {
queue.clear();
}
}
}
@Override
public boolean isDisposed() {
return disposed;
}
void schedule() {
if (getAndIncrement() == 0) {
worker.schedule(this);
}
}
void drainNormal() {
int missed = 1;
final SimpleQueue q = queue;
final Observer super T> a = downstream;
for (;;) {
if (checkTerminated(done, q.isEmpty(), a)) {
return;
}
for (;;) {
boolean d = done;
T v;
try {
v = q.poll();//取出
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
disposed = true;
upstream.dispose();
q.clear();
a.onError(ex);
worker.dispose();
return;
}
boolean empty = v == null;
if (checkTerminated(d, empty, a)) {
return;
}
if (empty) {
break;
}
a.onNext(v);//发送给observer
}
missed = addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
void drainFused() {
int missed = 1;
for (;;) {
if (disposed) {
return;
}
boolean d = done;
Throwable ex = error;
if (!delayError && d && ex != null) {
disposed = true;
downstream.onError(error);
worker.dispose();
return;
}
downstream.onNext(null);
if (d) {
disposed = true;
ex = error;
if (ex != null) {
downstream.onError(ex);
} else {
downstream.onComplete();
}
worker.dispose();
return;
}
missed = addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
@Override
public void run() {
if (outputFused) {
drainFused();
} else {
drainNormal();
}
}
//检查是否已经结束或数据已经发送完毕
boolean checkTerminated(boolean d, boolean empty, Observer super T> a) {
//清空
if (disposed) {
queue.clear();
return true;
}
if (d) {
Throwable e = error;
//延迟错误
if (delayError) {
if (empty) {
disposed = true;
if (e != null) {
a.onError(e);
} else {
a.onComplete();
}
worker.dispose();
return true;
}
} else {//发送错误
if (e != null) {
disposed = true;
queue.clear();
a.onError(e);
worker.dispose();
return true;
} else
if (empty) {
disposed = true;
a.onComplete();
worker.dispose();
return true;
}
}
}
return false;
}
@Override
public int requestFusion(int mode) {
if ((mode & ASYNC) != 0) {
outputFused = true;
return ASYNC;
}
return NONE;
}
@Nullable
@Override
public T poll() throws Exception {
return queue.poll();
}
@Override
public void clear() {
queue.clear();
}
@Override
public boolean isEmpty() {
return queue.isEmpty();
}
}
代码很长,不要在意这些细节,重点的已经注释说明了。
总的来说,具体就是在onNext方法接收到数据时先将数据入队,然后再切换到worker所在的线程(即传递进来的线程)取出发送给Observer,所以说observeOn执行在调用它的线程,之后接受数据是在设置的线程(例子给出的是主线程),由此实现了线程切换,就是这么简单!
(2)subscribeOn
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Observable subscribeOn(Scheduler scheduler) {
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
return RxJavaPlugins.onAssembly(new ObservableSubscribeOn(this, scheduler));//又是它
}
老规矩,经过前面的分析,相信接下来的大伙能够看懂了。
ObservableSubscribeOn:
public ObservableSubscribeOn(ObservableSource source, Scheduler scheduler) {
super(source);
this.scheduler = scheduler;
}
subscribeActual:
@Override
public void subscribeActual(final Observer super T> observer) {
final SubscribeOnObserver parent = new SubscribeOnObserver(observer);
observer.onSubscribe(parent);
parent.setDisposable(scheduler.scheduleDirect(new SubscribeTask(parent)));
}//将线程的操作加入到Disposeble管理之中
然后就是适配器SubscribeOnObserver:
static final class SubscribeOnObserver extends AtomicReference implements Observer, Disposable {
private static final long serialVersionUID = 8094547886072529208L;
final Observer super T> downstream;
final AtomicReference upstream;
SubscribeOnObserver(Observer super T> downstream) {
this.downstream = downstream;
this.upstream = new AtomicReference();
}
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.setOnce(this.upstream, d);
}
@Override
public void onNext(T t) {
downstream.onNext(t);
}
@Override
public void onError(Throwable t) {
downstream.onError(t);
}
@Override
public void onComplete() {
downstream.onComplete();
}
@Override
public void dispose() {
DisposableHelper.dispose(upstream);
DisposableHelper.dispose(this);
}
@Override
public boolean isDisposed() {
return DisposableHelper.isDisposed(get());
}
void setDisposable(Disposable d) {
DisposableHelper.setOnce(this, d);
}
}
跟前面的差不多,此处就不多解释,重点介绍下
parent.setDisposable(scheduler.scheduleDirect(new SubscribeTask(parent)));
void setDisposable(Disposable d) {
DisposableHelper.setOnce(this, d);//立马执行
}
然后是scheduleDirect:
@NonNull
public Disposable scheduleDirect(@NonNull Runnable run) {
return scheduleDirect(run, 0L, TimeUnit.NANOSECONDS);
}
@NonNull
public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) {
final Worker w = createWorker();
final Runnable decoratedRun = RxJavaPlugins.onSchedule(run);
DisposeTask task = new DisposeTask(decoratedRun, w);
w.schedule(task, delay, unit);//在worker的线程执行任务
return task;
}
与observeOn不同的是,这里传递进来的runnable里面就执行了,而不用入队后切换线程。
5.总结
observeOn和subscribeOn虽有差异,但执行流程相似,这里就简单附上流程图吧:
切换线程那一步很重要哦!
原创文章,转载请附上https://www.jianshu.com/p/ad5909baa913