Android框架源码分析——RxJava&Schedule源码分析

1、线程切换使用实例

Observable.create(object:ObservableOnSubscribe<String>{
    override fun subscribe(e: ObservableEmitter<String>) {
        e.onNext("A")
    }
})  .subscribeOn(Schedulers.io()) //设置订阅线程
    .observeOn(AndroidSchedulers.mainThread()) //设置观察者线程
    .subscribe()
  • onSubscribe():执行线程就是创建Observable的当前线程,并不订阅线程、观察者线程的影响,因为从源码中无论看出BasicFuseableObserver还是继承类中针对onSubscribe()都没有进行线程操作
public final void onSubscribe(Disposable s) {
        if (beforeDownstream()) {
            actual.onSubscribe(this);//调用下游的onSubscribe(),层层传递
            afterDownstream();
        }
}

2、observeOn():设置观察者线程

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));
    }
}
2.1、 Scheduler.Worker

这里设置的是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():切换线程并响应发送事件
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;
    }
}
  • ObserveOnObserver.run():切换线程后执行的任务
@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传递响应,此时已经找切换的线程中执行了
        }
    }
}

3、subscribeOn():设置订阅线程

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

  • SubscribeTask:保存观察者,并触发上层Observable的subscribe()执行事件发送
final class SubscribeTask implements Runnable {
    SubscribeTask(SubscribeOnObserver<T> parent) {
        this.parent = parent; // 保存Observer
    }
    @Override
    public void run() {
        source.subscribe(parent);  //在切换的线程中执行run()时触发上层发送事件
    }
}
  • scheduler.scheduleDirect(…):切换线程
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()中执行一下逻辑:

  1. 调用createWorker()创建线程Workrt,传入缓存Worker池
  2. 创建DisposeTask保存Worker和Runnable
  3. 调用Worker执行DisposeTask
  • EventLoopWorker:执行任务
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中方法
}
  • 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;
    } 
}
  • executor.submit(task)任务最后会最终执行SubscribeTask.run()方法,在run()中调用上层被观察者的subscribe()方法发送事件,此时执行发送事件的线程就切换到设置的订阅线程

4、Schedule

  • ObserverOn()和SubscribeOn()都使用到Schedule去切换工作线程,然后分别在不同的线程中执行操作,二者都是通过创建工作Worker执行事件达到线程切换的目的
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;
}
}
  1. 总结线程调度:首先传入Scheduler的继承类,调用scheduleDirect()执行任务,任务第一步调用重写方法createWorker()创建具体实现的工作Worker,然后调用Worler.Schedule()执行具体任务,内部创建线程执行达到切换的目的;
  • IoScheduler:创建和缓存一组线程池,并使用线程池调度程序
public final class IoScheduler extends Scheduler {
}
  1. 设置方法,这里设置RxJava内置线程
Schedulers.io()
  1. 重写createWorker()创建具体对应的Worker对象
public Worker createWorker() {
  return new EventLoopWorker(pool.get()); //参数:CachedWorkerPool缓存池
}
  1. EventLoopWorker——IoScheduler中的Worker具体实现类,在schedule()中调用工作线程Threadworker执行任务
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);
}
  1. ThreadWorker——真正执行任务的地方,内部初始化线程池并执行Callable,在Callable中触发被观察者事件的发送
 //初始化线程池
 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;
}
  1. CachedWorkerPool——首先创建Worker实例,内部会使用传入的线程工厂创建线程池,并将工作线程保存在allWorkers中,当任务完成后调用release()释放并缓存线程
//获取工作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); //添加到缓存队列
}
  • 总结线程工作流程:
  1. 在设置中传入IOSchedule实例
  2. 切换线程时调用IOSchedule.scheduleDirect()执行任务
  3. 调用IOSchedule重写的createWorker()创建EventLoopWorker实例
  4. EventLoopWorker中首先从IOSchedule内部缓存池中获取ThreadWorker实例,如果没有则创建具体实例并返回
  5. 调用Worker.schedule()方法执行任务,schedule()方法中调用ThreadWorker.scheduleActual()
  6. ThreadWorker.scheduleActual()中调用线程池执行任务
  7. 执行结束后缓存ThreadWorker实例

你可能感兴趣的:(Android框架源码分析——RxJava&Schedule源码分析)