RxJava源码之create,初窥门道 |
您所在的位置:网站首页 › 初窥门道细看像是深渊吗 › RxJava源码之create,初窥门道 |
简单学习分析RxJava的源码,预计会写三篇 create Schedulers.newThread() zip create关于坊间对于RxJava的定义都略有耳闻,除了其响亮的旗号响应式编程之外,大概所知至多应是其基于常见设计模式之观察者模式的框架设计理念。作为一枚Java工程师,理应知道JDK库内置了观察者模式的实现API接口,至于二者之间有何区别不妨自行了解,本文仅关注RxJava的具体实现思路。 在阅读源码之前,先写一个简单的Demo做为实践是一件极其必要的事,若不先知其然就欲知其所以然,就有些主次颠倒。不过不要紧,我这里提供了一个极其简单的Demo可供运行,但是Demo的运行过程也不仅仅只在运行,我们还要将其中涉及到的关键类找出来,并通过IDE找到顶层接口设计。从顶层接口的设计辅之以Demo的运行思路即可俯瞰该模块的设计思路。 Observable.create(new ObservableOnSubscribe() { @Override public void subscribe(ObservableEmitter emitter) throws Exception { System.out.println("thread name : " + Thread.currentThread().getName()); emitter.onNext("ABC"); } }).subscribe(new Observer() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(String t) { System.out.println("thread name : " + Thread.currentThread().getName()); System.out.println("create string value : " + t); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); 顶级接口设计找到顶级接口,是完成源码阅读的首要任务,顶层接口可帮助我们俯瞰整体架构设计。 Observable可观察类,我认为可以理解为被观察者,查阅其注释如下: /** * The Observable class is the non-backpressured, optionally multi-valued base reactive class that * offers factory methods, intermediate operators and the ability to consume synchronous * and/or asynchronous reactive dataflows. * .... **/ public abstract class Observable implements ObservableSource { //... }在注释中完全可以提取到很关键的信息:非背压,提供工厂方法、操作符以及同步异步的响应式数据流操作能力,也就是说它的根本能力应该是提供我们常见的关键API入口。同时,它实现了一个接口ObservableSource。 ObservableSource字面理解,可观察源,查阅注释如下: /** * Represents a basic, non-backpressured {@link Observable} source base interface, * consumable via an {@link Observer}. * * @param the element type * @since 2.0 */ public interface ObservableSource { /** * Subscribes the given Observer to this ObservableSource instance. * @param observer the Observer, not null * @throws NullPointerException if {@code observer} is null */ void subscribe(@NonNull Observer |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |