一:RxJava执行流程:

RxJava简单使用

private final String tag = getClass().getSimpleName();
//数据源,被观察对象
Observable<String> obser = Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
Log.d(tag,"emit 1");
emitter.onNext("t1");
Log.d(tag,"emit 2");
emitter.onNext("t2");
Log.d(tag,"emit 3");
emitter.onNext("t3");
Log.d(tag,"emit ");
emitter.onComplete();
}
}); private void observer_test(){
Observer<String> dnObser = new Observer<String>() {//观察者,处理对应事件
@Override
public void onSubscribe(Disposable d) {
Log.d(tag,"onSubscribe");
} @Override
public void onNext(String s) {
Log.d(tag,"onNext "+s);
} @Override
public void onError(Throwable e) {
Log.e(tag,"onError");
} @Override
public void onComplete() {
Log.d(tag,"onComplete");
}
};
obser.subscribe(dnObser);
});
}

从例子中看出RxJava主要组成:

Observable:被观察者,被观察者本身

ObservableOnSubscribe:通知观察者执行哪些行为

Observer:观察者,通过实现对应方法做具体处理

订阅过程处理:

  @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");
    //开始调用ObservableOnSubscribe subscribe
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);

查看subscribe方法为抽象方法,具体实现为ObservableCreate,从Observabel的create方法可以知道

@CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public static <T> Observable<T> create(ObservableOnSubscribe<T> source) {
ObjectHelper.requireNonNull(source, "source is null");
return RxJavaPlugins.onAssembly(new ObservableCreate<T>(source));
}

查看Observable内的源码

public final class ObservableCreate<T> extends Observable<T> {
final ObservableOnSubscribe<T> source; public ObservableCreate(ObservableOnSubscribe<T> source) {
this.source = source;
} @Override
protected void subscribeActual(Observer<? super T> observer) {
CreateEmitter<T> parent = new CreateEmitter<T>(observer);
observer.onSubscribe(parent); try {//这里调用ObservableOnSubscribe 的subscribe方法,开始执行事件流程
source.subscribe(parent);
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
parent.onError(ex);
}
}
......
}

二:数据转换

收到Observable的消息之前我们有可能会对数据流进行处理,例如map()、flatMap()、fllter()等方法,

这里使用了map()方法,它接收了observeable的数据并将通过该方法将数据进行转换后的新数据发出去,即做了中间转化

 public final <R> Observable<R> map(Function<? super T, ? extends R> mapper) {
ObjectHelper.requireNonNull(mapper, "mapper is null");
return RxJavaPlugins.onAssembly(new ObservableMap<T, R>(this, mapper));
}

rxjava2使用了Function接口提供转换功能,

public interface Function<T, R> {
//将T类型数据转化为R处理
@NonNull
R apply(@NonNull T t) throws Exception;
}

具体操作交给ObservableMap内部类MapObserver处理

public final class ObservableMap<T, U> extends AbstractObservableWithUpstream<T, U> {
final Function<? super T, ? extends U> function; public ObservableMap(ObservableSource<T> source, Function<? super T, ? extends U> function) {
super(source);
this.function = function;
} @Override
public void subscribeActual(Observer<? super U> t) {
source.subscribe(new MapObserver<T, U>(t, function));
} static final class MapObserver<T, U> extends BasicFuseableObserver<T, U> {
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) {
....... U v;
try {
//调用Function apply处理
v = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper function returned a null value.");
} catch (Throwable ex) {
fail(ex);
return;
}//将转换后的类型再传递给原Obsever
actual.onNext(v);
}
......
}
}

MapObserver实现Observer,持有传入的Observer,通过Function的mapper.apply(t)进行转换后再传递给原observer onNext()

三:任务调度(scheduler)

通过使用subscribeOn()、observeOn()方法传入对应的Scheduler去指定每个操作应该运行在何种线程之中

Observable.create(...)
    ...
    .subscribeOn(Schedulers.io()) // 指定 subscribe() 发生在 IO 线程
    ...
    .subscribeOn(Schedulers.newThread())
    ...
    .subscribeOn(Schedulers.computation())
    ...
        .observeOn(AndroidSchedulers.mainThread()) // 指定 Subscriber 的回调发生在主线程
        .subscribe(...)

 @CheckReturnValue
@SchedulerSupport(SchedulerSupport.CUSTOM)
public final Observable<T> subscribeOn(Scheduler scheduler) {
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
return RxJavaPlugins.onAssembly(new ObservableSubscribeOn<T>(this, scheduler));
}

创建了一个新的Observable,并为新的Observable创建了新的计划表ObservableSubscribeOn对象,新的计划表保存了原始Observable对象和调度器scheduler

public final class ObservableSubscribeOn<T> extends AbstractObservableWithUpstream<T, T> {
final Scheduler scheduler; 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); s.onSubscribe(parent);
//调用了Scheduler的shedule方法,创建Runable内部执行原obseverable sbscribe
parent.setDisposable(scheduler.scheduleDirect(new Runnable() {
@Override
public void run() {
source.subscribe(parent);
}
}));
}
...
}

以IOScheduler为例

Scheduler schdule

@NonNull
public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) {
final Worker w = createWorker(); final Runnable decoratedRun = RxJavaPlugins.onSchedule(run);
//调用Work 切换执行线程
w.schedule(new Runnable() {
@Override
public void run() {
try {
decoratedRun.run();
} finally {
w.dispose();
}
}
}, delay, unit); return w;
}
    @NonNull
@Override
public Worker createWorker() {
return new EventLoopWorker(pool.get());
} public int size() {
return pool.get().allWorkers.size();
} static final class EventLoopWorker extends Scheduler.Worker {
private final CompositeDisposable tasks;
private final CachedWorkerPool pool;
private final ThreadWorker threadWorker; final AtomicBoolean once = new AtomicBoolean(); EventLoopWorker(CachedWorkerPool pool) {
this.pool = pool;
this.tasks = new CompositeDisposable();
this.threadWorker = pool.get();
}
。。。。 @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);
}
} static final class ThreadWorker extends NewThreadWorker {
private long expirationTime; ThreadWorker(ThreadFactory threadFactory) {
super(threadFactory);
this.expirationTime = 0L;
} 。。。
}

我们从缓存池里拿到需要的worker并作了一层封装成为EventLoopWorker:最后调用NewThreadWorker 的scheduleActual

看NewThreadWorker实现:

public class NewThreadWorker extends Scheduler.Worker implements Disposable {
private final ScheduledExecutorService executor;//线程执行器
... public NewThreadWorker(ThreadFactory threadFactory) {
executor = SchedulerPoolFactory.create(threadFactory);
}
...... //通过Execotor来执行上面传递过来的Runable对象,达到在不同类型线程来执行调用Observer方法
public Disposable scheduleDirect(final Runnable run, long delayTime, TimeUnit unit) {
Runnable decoratedRun = RxJavaPlugins.onSchedule(run);
try {
Future<?> f;
if (delayTime <= 0) {
f = executor.submit(decoratedRun);//提交到线程池执行
} else {
f = executor.schedule(decoratedRun, delayTime, unit);
}
return Disposables.fromFuture(f);
} catch (RejectedExecutionException ex) {
RxJavaPlugins.onError(ex);
return EmptyDisposable.INSTANCE;
}
}

再看看observeOn

public final Observable<T> observeOn(Scheduler scheduler, boolean delayError, int bufferSize) {
ObjectHelper.requireNonNull(scheduler, "scheduler is null");
ObjectHelper.verifyPositive(bufferSize, "bufferSize");
return RxJavaPlugins.onAssembly(new ObservableObserveOn<T>(this, scheduler, delayError, bufferSize));
}
public final class ObservableObserveOn<T> extends AbstractObservableWithUpstream<T, T> {
final Scheduler scheduler;
final boolean delayError;
final int bufferSize;
public ObservableObserveOn(ObservableSource<T> source, Scheduler scheduler, boolean delayError, int bufferSize) {
super(source);
this.scheduler = scheduler;
this.delayError = delayError;
this.bufferSize = bufferSize;
} @Override
protected void subscribeActual(Observer<? super T> observer) {
if (scheduler instanceof TrampolineScheduler) {
source.subscribe(observer);
} else {
Scheduler.Worker w = scheduler.createWorker(); source.subscribe(new ObserveOnObserver<T>(observer, w, delayError, bufferSize));
}
} static final class ObserveOnObserver<T> extends BasicIntQueueDisposable<T>
implements Observer<T>, Runnable { private static final long serialVersionUID = 6576896619930983584L;
final Observer<? super T> actual;
final Scheduler.Worker worker;
final boolean delayError;
final int bufferSize; SimpleQueue<T> queue; Disposable s; Throwable error;
volatile boolean done; volatile boolean cancelled; int sourceMode; boolean outputFused; ObserveOnObserver(Observer<? super T> actual, Scheduler.Worker worker, boolean delayError, int bufferSize) {
this.actual = actual;
this.worker = worker;
this.delayError = delayError;
this.bufferSize = bufferSize;
} @Override
public void onSubscribe(Disposable s) {
... actual.onSubscribe(this);
}
} @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() {//任务调度,交给线程池回调Runable
if (getAndIncrement() == 0) {
worker.schedule(this);
}
}
    @Override
        public void run() {//回调处理,代理调用原Observer方法
            if (outputFused) {
                drainFused();
            } else {
                drainNormal();
            }
        }
        
   void drainNormal() {
            int missed = 1;

            final SimpleQueue<T> q = queue;
            final Observer<? super T> a = actual;
.......

                    a.onNext(v);
                ......
            }
        }       
... }
}

这里通过ObservableObserveOn代理,实现Observer observeOn线程切换处理

未完待续。。。

RxJava简要分析的更多相关文章

  1. RxJava && Agera 从源码简要分析基本调用流程(2)

    版权声明:本文由晋中望原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/124 来源:腾云阁 https://www.qclo ...

  2. Activity源码简要分析总结

    Activity源码简要分析总结 摘自参考书籍,只列一下结论: 1. Activity的顶层View是DecorView,而我们在onCreate()方法中通过setContentView()设置的V ...

  3. Google发布SSLv3漏洞简要分析报告

    今天上午,Google发布了一份关于SSLv3漏洞的简要分析报告.根据Google的说法,该漏洞贯穿于所有的SSLv3版本中,利用该漏洞,黑客可以通过中间人攻击等类似的方式(只要劫持到的数据加密两端均 ...

  4. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(34)-文章发布系统①-简要分析

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(34)-文章发布系统①-简要分析 系列目录 最新比较闲,为了学习下Android的开发构建ASP.NET ...

  5. CVE-2015-5122 简要分析(2016.4)

    CVE-2015-5122 简要分析 背景 最近在学习Flash漏洞的分析,其与IE漏洞的分析还是有诸多的不同(不便)之处,折腾了一阵子终于克服了没有符号表.Flash的超时定时器等问题.所以找到了去 ...

  6. Java7中的ForkJoin并发框架初探(中)——JDK中实现简要分析

    原文发表于 2013 年 8 月 28 日 由 三石 根据前文描述的Doug Lea的理论基础,在JDK1.7中已经给出了Fork Join的实现.在Java SE 7的API中,多了ForkJoin ...

  7. [转]Java7中的ForkJoin并发框架初探(中)——JDK中实现简要分析

    详见: http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp85   根据前文描述的Doug Lea的理论基础,在JDK1.7中已经给 ...

  8. ITS简要分析流程(using Qiime)

    Qiime安装 参考资料:http://blog.sina.com.cn/s/blog_83f77c940101h2rp.html Qiime script官方说明http://qiime.org/s ...

  9. Android初级教程通过简要分析“土司”源码,来自实现定义土司理论探讨

    由于系统自带的土司瞬间即逝,而且非常难看.因此我们就希望自定义自己的土司风格.有些实例就是基于自定义土司完成的,例如金山卫士的火箭发射,基本原理就是个土司.但是在做出自己的土司风格之前,还是要简要分析 ...

  10. Android Hal层简要分析

    Android Hal层简要分析 Android Hal层(即 Hardware Abstraction Layer)是Google开发的Android系统里上层应用对底层硬件操作屏蔽的一个软件层次, ...

随机推荐

  1. 2.4 在DispatcherServlet的service方法中,通过ServletPath获取对应的Controller对象

    @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws Se ...

  2. list.ftl

    1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 < ...

  3. vue.use的原理

    接收一个vue组件 该组件应该有个方法,install customComponent.install=function(Vue){ vue.Component('name',custemCompon ...

  4. linux 多级时间轮应用场景

    参考链接: https://www.163.com/dy/article/GMGUO9UV05421U51.html

  5. ns 状态为Terminating

    kubectl delete ns harbor --force --grace-period=0harbor状态为Terminatingkubectl proxy --port=6880kubect ...

  6. VLC播放器 for Mac OS X

    ​ VLC 是一款自由.开源的跨平台多媒体播放器及框架,可播放大多数多媒体文件,以及 DVD.音频 CD.VCD 及各类流媒体协议. https://www.videolan.org/vlc/down ...

  7. unittestreport生成报告介绍

    ​ unittestreport主要有以下几个作用 接口用例HTML 测试报告生成. 测试用例失败重运行. 发送测试结果及报告到邮箱. 发送报告到钉钉群. 安装unittestreport: pip3 ...

  8. web开发(2): html标签/web语义化

    chapter2 html 标签 在sublime中敲入!, 按tab 进行拓展,得到如下框架 <!DOCTYPE html> <html lang="en"&g ...

  9. netmiko批量操作华为设备

    from concurrent.futures import ThreadPoolExecutorimport timeimport netmikoimport osfrom threading im ...

  10. PyCharm如何实现控制台换行显示

    举个例子 我现在想要看输出结果的所有数据然后再控制台输出的信息如下: 本来输出的内容有很多,但由于只显示了一行,因此想要看全部的内容还需要拖拉滚动条,挺麻烦的,而且看着也不方便,怎么让控制台信息全都直 ...