RxJava2.0第一篇

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

Getting started

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表达式详解
http://www.cnblogs.com/knowledgesea/p/3163725.html
----ps结束

RxJava 2 features several base classes 
  • io.reactivex.Flowable : 0..N flows, supporting Reactive-Streams and backpressure
  • io.reactivex.Observable: 0..N flows, no backpressure
  • io.reactivex.Single: a flow of 恰好地1 item or an error
  • io.reactivex.Completable: a flow without items but only a completion or error signal
  • io.reactivex.Maybe: a flow with no items, exactly one item or an error
Flowable<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);

Typically, you can move computations or blocking IO to some other thread via  subscribeOn . Once the data is ready, you can make sure they get processed on the foreground or GUI thread via  observeOn .
These are available on all JVM platforms but some specific platforms, such as Android, have their own typical Schedulers defined: AndroidSchedulers.mainThread()SwingScheduler.instance() or JavaFXSchedulers.gui().
 In RxJava the default Schedulers run on daemon threads, which means once the Java main thread exits, they all get stopped and background computations may never happen. 

你可能感兴趣的:(RxJava2.0第一篇)