Observable.create(object:ObservableOnSubscribe<String>{
override fun subscribe(e: ObservableEmitter<String>) {
e.onNext("A")
}
}) .subscribeOn(Schedulers.io()) //设置订阅线程
.observeOn(AndroidSchedulers.mainThread()) //设置观察者线程
.subscribe()
public final void onSubscribe(Disposable s) {
if (beforeDownstream()) {
actual.onSubscribe(this);//调用下游的onSubscribe(),层层传递
afterDownstream();
}
}
public final Observable<T> observeOn(Scheduler scheduler) {
return observeOn(scheduler, false, bufferSize());
}
public final Observable<T> observeOn(Scheduler scheduler, boolean delayError, int bufferSize) {
return RxJavaPlugins.onAssembly(new ObservableObserveOn<T>(this, scheduler, delayError, bufferSize));
}
observeOn()操作符最终创建的是ObservableObserveOn对象,在ObservableObserveOn中保存设置的线程,并在执行时切换线程,在ObservableObserveOn的subscribeActual()中创建工作线程保存在Observer中,所以Observe只会作用于下游观察者
public ObservableObserveOn(ObservableSource<T> source, Scheduler scheduler, boolean delayError, int bufferSize) {
super(source); // 保存Observable
this.scheduler = scheduler; //保存Schedule
this.delayError = delayError;
this.bufferSize = bufferSize;
}
//订阅执行的方法
@Override
protected void subscribeActual(Observer<? super T> observer) {
if (scheduler instanceof TrampolineScheduler) { //设置为TrampolineScheduler直接执行
source.subscribe(observer);
} else {
Scheduler.Worker w = scheduler.createWorker(); //
source.subscribe(new ObserveOnObserver<T>(observer, w, delayError, bufferSize));
}
}
这里设置的是AndroidSchedulers.mainThread(),在AndroidSchedulers中创建HandlerScheduler对象,这里使用的是Looper.getMainLooper()工作队列,所以观察者执行会在主线程中执行
public final class AndroidSchedulers {
private static final class MainHolder {
//使用主线线程队列创建HandlerScheduler,后面任务都会发送到MainLooper中
static final Scheduler DEFAULT = new HandlerScheduler(new Handler(Looper.getMainLooper()));
}
}
//createWorker()
@Override
public Worker createWorker() {
return new HandlerWorker(handler); // 创建HandlerWorker
}
由上面订阅分析知道,任务的执行会传递到ObserveOnObserver的onNext()中
ObserveOnObserver(Observer<? super T> actual, Scheduler.Worker worker, boolean delayError, int bufferSize) {
this.actual = actual; //下游的Observer
this.worker = worker; //创建的工作线程
this.delayError = delayError;
this.bufferSize = bufferSize;
}
@Override
public void onNext(T t) {
if (sourceMode != QueueDisposable.ASYNC) {
queue.offer(t); //添加任务到队列
}
schedule();
}
void schedule() {
if (getAndIncrement() == 0) {
worker.schedule(this); //执行队列任务,此处调用的是HandlerWorker
}
}
在ObserveOnObserver的onNext()中首先将发送的事件加入队列queue中,然后调用schedule()方法,调用worker.schedule()执行队列任务,这理创建的是HandlerWorker对象,在HandlerWorker的schedule()中发送消息到MainLooper,最终方法执行ObserveOnObserver.run()
private static final class HandlerWorker extends Worker {
private final Handler handler;
HandlerWorker(Handler handler) {
this.handler = handler; // 保存Handler
}
@Override
public Disposable schedule(Runnable run, long delay, TimeUnit unit) {
run = RxJavaPlugins.onSchedule(run);
ScheduledRunnable scheduled = new ScheduledRunnable(handler, run);
Message message = Message.obtain(handler, scheduled);
message.obj = this;
handler.sendMessageDelayed(message, Math.max(0L, unit.toMillis(delay)));
return scheduled;
}
}
@Override
public void run() {
if (outputFused) {
drainFused();
} else {
drainNormal(); //执行主线程中的消息任务
}
}
void drainNormal() {
int missed = 1;
final SimpleQueue<T> q = queue; //获取队列
final Observer<? super T> a = actual; //获取观察者Observer
for (;;) {
for (;;) {
boolean d = done;
T v;
try {
v = q.poll(); //从队列中取出数据
} catch (Throwable ex) {
return;
}
a.onNext(v); //向下游Observer传递响应,此时已经找切换的线程中执行了
}
}
}
public final Observable<T> subscribeOn(Scheduler scheduler) {
return RxJavaPlugins.onAssembly(new ObservableSubscribeOn<T>(this, scheduler)); //创建ObservableSubscribeOn实例
}
public ObservableSubscribeOn(ObservableSource<T> source, Scheduler scheduler) {
super(source);
this.scheduler = scheduler;
}
@Override
public void subscribeActual(final Observer<? super T> s) {
final SubscribeOnObserver<T> parent = new SubscribeOnObserver<T>(s); //封装下游Observer
s.onSubscribe(parent); //执行onSubscribe()
parent.setDisposable(scheduler.scheduleDirect(new SubscribeTask(parent))); //
}
订阅线程操作符对应的 ObservableSubscribeOn类,ObservableSubscribeOn封装下游观察者,在ObservableSubscribeOn的subscribeActual中创建SubscribeTask对象,然后调用scheduler.scheduleDirect()执行SubscribeTask
final class SubscribeTask implements Runnable {
SubscribeTask(SubscribeOnObserver<T> parent) {
this.parent = parent; // 保存Observer
}
@Override
public void run() {
source.subscribe(parent); //在切换的线程中执行run()时触发上层发送事件
}
}
public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) {
final Worker w = createWorker(); //(1)
final Runnable decoratedRun = RxJavaPlugins.onSchedule(run);
DisposeTask task = new DisposeTask(decoratedRun, w); //
w.schedule(task, delay, unit); //(2)执行任务
return task;
}
@Override
public Worker createWorker() {
return new EventLoopWorker(pool.get()); //
}
scheduleDirect()中执行一下逻辑:
EventLoopWorker(CachedWorkerPool pool) {
this.pool = pool;
this.tasks = new CompositeDisposable();
this.threadWorker = pool.get(); //获取Worker实例,此处获取的是NewThreadWorker实例
}
public Disposable schedule(@NonNull Runnable action, long delayTime, @NonNull TimeUnit unit) {
return threadWorker.scheduleActual(action, delayTime, unit, tasks); //(3)执行NewThreadWorker中方法
}
private final ScheduledExecutorService executor = SchedulerPoolFactory.create(threadFactory);//线程池
public Disposable scheduleDirect(final Runnable run, long delayTime, TimeUnit unit) {
ScheduledDirectTask task = new ScheduledDirectTask(RxJavaPlugins.onSchedule(run));
try {
Future<?> f;
if (delayTime <= 0L) {
f = executor.submit(task); //(4)使用线程池执行任务
} else {
f = executor.schedule(task, delayTime, unit);
}
return task;
}
}
public abstract class Scheduler {
public abstract Worker createWorker(); //(1)创建具体工作Worker
//(2)执行工作的方法,最终调用Worker子类中重写的schedule()
public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) {
final Worker w = createWorker();
w.schedule(task, delay, unit); 调用Worker.schedule()
return task;
}
}
public final class IoScheduler extends Scheduler {
}
Schedulers.io()
public Worker createWorker() {
return new EventLoopWorker(pool.get()); //参数:CachedWorkerPool缓存池
}
EventLoopWorker(CachedWorkerPool pool) {
this.pool = pool; //保存传入的缓存池
this.tasks = new CompositeDisposable();
this.threadWorker = pool.get(); //从缓存池中获取工作线程
}
//
public Disposable schedule(@NonNull Runnable action, long delayTime, @NonNull TimeUnit unit) {
return threadWorker.scheduleActual(action, delayTime, unit, tasks);
}
//初始化线程池
private final ScheduledExecutorService executor = SchedulerPoolFactory.create(threadFactory);
@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);
try {
if (delayTime <= 0) { //使用线程池执行任务
f = executor.submit((Callable<Object>)sr);
} else {
f = executor.schedule((Callable<Object>)sr, delayTime, unit);
}
sr.setFuture(f);
}
return sr;
}
//获取工作Worker
ThreadWorker get() {
while (!expiringWorkerQueue.isEmpty()) { //如果缓存池不为空,取出Worker返回
ThreadWorker threadWorker = expiringWorkerQueue.poll();
if (threadWorker != null) {
return threadWorker;
}
}
ThreadWorker w = new ThreadWorker(threadFactory); //
allWorkers.add(w);
return w;
}
void release(ThreadWorker threadWorker) { //添加缓存的ThreadWorker
threadWorker.setExpirationTime(now() + keepAliveTime); //设置有效期
expiringWorkerQueue.offer(threadWorker); //添加到缓存队列
}