响应式编程
说道rxjava,就要提到响应式编程
响应式编程是一种基于异步数据流概念的编程模式。
数据流就像一条河:它可以被观测,被过滤,被操作,或者为新的消费者与另外一条流合并为一条新的流。
简介
RxJava可以浓缩为异步两个字,其核心的东西不外乎两个, Observable(被观察者) 和 Observer(观察者)。Observable可以发出一系列的 事件(例如网络请求、复杂计算、数据库操作、文件读取等),事件执行结束后交给Observer的回调处理。
使用
Observable.create(new ObservableOnSubscribe() {
@Override
public void subscribe(@NonNull ObservableEmitter e) throws Exception {
e.onNext("5555555");
}
}).subscribe(new Observer() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull String o) {
Log.e("onNext",o);
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
}
看源码
先看被观察者Observable的create方法,Observable是一个抽象类
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static Observable create(ObservableOnSubscribe source) {
//null判断
ObjectHelper.requireNonNull(source, "source is null");
//追踪该代码
return RxJavaPlugins.onAssembly(new ObservableCreate(source));
}
@NonNull
public static Observable onAssembly(@NonNull Observable source) {
Function super Observable, ? extends Observable> f = onObservableAssembly;
if (f != null) {
return apply(f, source);
}
//将Observable返回给我们
return source;
}
//ObservableCreate是Observable(被观察者)的子类
public final class ObservableCreate extends Observable {
final ObservableOnSubscribe source;
public ObservableCreate(ObservableOnSubscribe source) {
this.source = source;
}
从上述代码可以看出,最终将Observable返回给了我们,那我们看看ObservableOnSubscribe是什么
public interface ObservableOnSubscribe {
/**
* Called for each Observer that subscribes.
* @param emitter the safe emitter instance, never null
* @throws Exception on error
*/
void subscribe(@NonNull ObservableEmitter emitter) throws Exception;
}
接下我们看Observer,这几个方法很熟悉
public interface Observer {
void onSubscribe(@NonNull Disposable d);
void onNext(@NonNull T t);
void onError(@NonNull Throwable e);
void onComplete();
}
然后我们看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, "Plugin returned null Observer");
//该方法是Observable的抽象方法,是Observable的子类实现的
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;
}
}
//我们知道ObservableCreate是Observable的子类,所以我们看ObservableCreate中实现的subscribeActual方法
@Override
protected void subscribeActual(Observer observer) {
//是ObservableCreate的静态内部类
CreateEmitter parent = new CreateEmitter(observer);
observer.onSubscribe(parent);
try {
//source就是我们在Observable.create方法中传入的ObservableOnSubscribe
source.subscribe(parent);
} catch (Exception e) {
Exceptions.throwIfFatal(ex);
parent.onError(ex);
}
}
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;
}
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());
}
}
线程调度
subscribeOn
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Observable subscribeOn(Scheduler scheduler) {
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
//这里代码和 Observable.create方法类似,直接看ObservableSubscribeOn
return RxJavaPlugins.onAssembly(new ObservableSubscribeOn(this, scheduler));
}
public final class ObservableSubscribeOn extends AbstractObservableWithUpstream {
final Scheduler scheduler;
public ObservableSubscribeOn(ObservableSource source, Scheduler scheduler) {
//Observable实现了ObservableSource这个接口的,所以这里的source是指我们刚才创建的那个Observable
super(source);
this.scheduler = scheduler;
}
@Override
public void subscribeActual(final Observer super T> s) {
final SubscribeOnObserver parent = new SubscribeOnObserver(s);
//Observer的onSubscribe方法,因为此时的Observable的subscribe
//方法发生在当前线程,所以Observer的onSubscribe方法的执行
//线程和当前调用Observable的subscribe方法的线程一致
s.onSubscribe(parent);
//SubscribeTask是一个Runnable,scheduler是线程调度对象,我们跟踪scheduleDirect方法
parent.setDisposable(scheduler.scheduleDirect(new SubscribeTask(parent)));
//将新的 Disposable 设置给 parent ,方便取消订阅关系,
}
static final class SubscribeOnObserver extends AtomicReference implements Observer, Disposable {
private static final long serialVersionUID = 8094547886072529208L;
final Observer super T> actual;
final AtomicReference s;
SubscribeOnObserver(Observer super T> actual) {
this.actual = actual;
this.s = new AtomicReference();
}
@Override
public void onSubscribe(Disposable s) {
DisposableHelper.setOnce(this.s, s);
}
@Override
public void onNext(T t) {
actual.onNext(t);
}
@Override
public void onError(Throwable t) {
actual.onError(t);
}
@Override
public void onComplete() {
actual.onComplete();
}
@Override
public void dispose() {
DisposableHelper.dispose(s);
DisposableHelper.dispose(this);
}
@Override
public boolean isDisposed() {
return DisposableHelper.isDisposed(get());
}
void setDisposable(Disposable d) {
DisposableHelper.setOnce(this, d);
}
}
final class SubscribeTask implements Runnable {
private final SubscribeOnObserver parent;
SubscribeTask(SubscribeOnObserver parent) {
this.parent = parent;
}
@Override
public void run() {
//执行了source(ObservableSource)的subscribe方法
//即上游Observable的subscribe方法
source.subscribe(parent);
}
}
}
subscribeOn方法返回了一个新的Observable,而这个新的Observable里面持有一个上一层Observable的引用。那个引用就是source。调用subscribeOn方法后,在他之前的和在他之后的代码执行的线程都是subscribeOn指定的线程,onSubscribe方法除外,因为Observable的subscribe方法发生在当前线程,所以Observer的onSubscribe方法的执行线程和当前调用Observable的subscribe方法的线程一致!
@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);
//包装了一下Runnable,DisposeTask还是一个Runnable
DisposeTask task = new DisposeTask(decoratedRun, w);
//schedule是Worker的抽象方法,在这我们追踪下IoScheduler的schedule方法
w.schedule(task, delay, unit);
return task;
}
@NonNull
@Override
public Disposable schedule(@NonNull Runnable action, long delayTime, @NonNull TimeUnit unit) {
if (tasks.isDisposed()) {
// don't schedule, we are unsubscribed
return EmptyDisposable.INSTANCE;
}
return threadWorker.scheduleActual(action, delayTime, unit, tasks);
}
@NonNull
public ScheduledRunnable scheduleActual(final Runnable run, long delayTime, @NonNull TimeUnit unit, @Nullable DisposableContainer parent) {
Runnable decoratedRun = RxJavaPlugins.onSchedule(run);
ScheduledRunnable sr = new ScheduledRunnable(decoratedRun, parent);
if (parent != null) {
if (!parent.add(sr)) {
return sr;
}
}
Future> f;
try {
if (delayTime <= 0) {
//通过线程池执行Runnable
f = executor.submit((Callable
我们看到最终调用了NewThreadWorker的中的线程池去执行我们传入的Runnable的run方法,即订阅方法中的线程始终由上游observable.subscribeOn方法来决定
subscribeOn第一次有效原理
由于订阅是由下而上的,所以最上面的subscribeOn方法是最后执行了,而subscribeOn方法返回的一个新的Observable里持有一个上一层Observable的引用,所以这里的线程是由上游observable.subscribeOn方法中传入的线程来决定,个人理解就像递归调用一样,直至调用到最上层的第一个subscribeOn方法.
举个栗子
public class Rx {
String name;
Rx rx;
public Rx(Rx rx,String name) {
this.name = name;
this.rx = rx;
}
public void subscribe(){
System.out.println(name+"subscribe线程:"+Thread.currentThread().getName());
if (rx == null){
System.out.println("最终执行"+name+"线程:"+Thread.currentThread().getName());
return;
}
new Thread(new Runnable() {
@Override
public void run() {
//调用上游rx的subscribe方法
rx.subscribe();
}
}).start();
}
}
public static void main(String[] args) {
Rx rx1 = new Rx(null, "rx1");
Rx rx2 = new Rx(rx1, "rx2");
Rx rx3 = new Rx(rx2, "rx3");
Rx rx4 = new Rx(rx3, "rx4");
rx4.subscribe();
}
结果如图
observeOn
@CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Observable observeOn(Scheduler scheduler, boolean delayError, int bufferSize) {
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
ObjectHelper.verifyPositive(bufferSize, "bufferSize");
//不啰嗦,直接看ObservableObserveOn的subscribeActual方法(真正的订阅方法)
return RxJavaPlugins.onAssembly(new ObservableObserveOn(this, scheduler, delayError, bufferSize));
}
@Override
protected void subscribeActual(Observer super T> observer) {
//TrampolineScheduler 表示当前线程
if (scheduler instanceof TrampolineScheduler) {
source.subscribe(observer);
} else {
Scheduler.Worker w = scheduler.createWorker();
//重点是ObserveOnObserver观察者
source.subscribe(new ObserveOnObserver(observer, w, delayError, bufferSize));
}
}
重点看ObserveOnObserver的onNext,onError,onComplete等方法
@Override
public void onNext(T t) {
if (done) {
return;
}
if (sourceMode != QueueDisposable.ASYNC) {
queue.offer(t);
}
//切换了线程
schedule();
}
@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();
}
void schedule() {
if (getAndIncrement() == 0) {
//我们已IO线程为例,追踪该方法
worker.schedule(this);
}
}
在Ioscheduler中找到实现的schedule方法
@NonNull
@Override
public Disposable schedule(@NonNull Runnable action, long delayTime, @NonNull TimeUnit unit) {
if (tasks.isDisposed()) {
// don't schedule, we are unsubscribed
return EmptyDisposable.INSTANCE;
}
//该方法即为我们追踪的subscribeOn中的相同的方法
return threadWorker.scheduleActual(action, delayTime, unit, tasks);
}
看到这里,我们应该了解了在线程调度过程中,subscribeOn和observeOn方法的区别,observeOn只要调用,就会切换下游事件的线程,而subscribeOn在他之前的和在他之后的代码执行的线程都是subscribeOn指定的线程,onSubscribe方法除外.