RxJava是Java的响应式扩展实现。这是一个组合了异步和基于事件编程的库,通过使用可观察序列。
它扩展了观察者模式用于支持data/events序列和添加操作符,这些操作符允许你以声明的方式把序列组合在一起,而不用担心底层线程,同步,线程安全和并发数据结构。
Version 2.x (Javadoc)
single dependency:Reactive-Streams
continued support for Java 6+ &Android2.3+
performance through design changes learned through the 1.x cycle and throughReactive-Streams-Commonsresearch project.
Java 8 lambda-friendly API
non-opinionated about source of concurrency (threads, pools, event loops, fibers, actors, etc)
async or synchronous execution
virtual time and schedulers for parameterized concurrency
The first step is to include RxJava 2 into your project, for example, as a Gradle compile dependency:
compile"io.reactivex.rxjava2:rxjava:2.x.y"
The second is to write the Hello World program
ps:可能的问题
1.not supported at this language level
解决:
方式一:
方式二:
andorid{}中加入
compileOptions {
targetCompatibility1.8
sourceCompatibility1.8
}
2.Error:Jack is required to support java 8 language features. Either enable Jack or remove sourceCompatibility JavaVersion.VERSION_1_8.
解决:
android {
...
defaultConfig {
...
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
3. Lambda表达式详解
io.reactivex.Flowable
: 0..N flows, supporting Reactive-Streams and backpressureio.reactivex.Observable
: 0..N flows, no backpressureio.reactivex.Single
: a flow of 恰好地1 item or an errorio.reactivex.Completable
: a flow without items but only a completion or error signalio.reactivex.Maybe
: a flow with no items, exactly one item or an errorFlowable<String> source = Flowable.fromCallable(() -> { Thread.sleep(1000); // imitate expensive computation return "Done"; }); Flowable<String> runBackground = source.subscribeOn(Schedulers.io()); Flowable<String> showForeground = runBackground.observeOn(Schedulers.single()); showForeground.subscribe(System.out::println, Throwable::printStackTrace); Thread.sleep(2000);
subscribeOn
. Once the data is ready, you can make sure they get processed on the foreground or GUI thread via
observeOn
.
Scheduler
s defined: AndroidSchedulers.mainThread()
, SwingScheduler.instance()
or JavaFXSchedulers.gui()
.Scheduler
s run on daemon threads, which means once the Java main thread exits, they all get stopped and background computations may never happen.