1.RxJava概念及原理
RxJava –
Reactive Extensions for the JVM – a library for composing asynchronous
and event-based programs using observable sequences for the Java VM.
为JVM设计使用可观测序列组成异步基于事件的程序库,核心使用观察者模式,以链式函数调用形式展示
2.x相对于1.x的改动
- 操作符基本没有变化,Action命名变化
Rx1.0-----------Rx2.0
Action1--------Action
Action1--------Consumer
Action2--------BiConsumer
后面的Action都去掉了,只保留了ActionN
Function和RxJava1.0相比,他们都增加了throws Exception,也就是说,在这些方法做某些操作就不需要try-catch。
Flowable.just("file.txt").map(name->Files.readLines(name)).subscribe(lines->System.out.println(lines.size()),Throwable::printStackTrace);
- 把支持背压的Observable单独抽出来到类Flowable
- Scheduler中移除了Schedulers.immediate()这个线程环境,io.reactivex.Scheduler这个抽象 类支持直接调度自定义线程任务
网友指出的rxjava1到2升级踩坑实战 ,不过官方提供了1.x到2.x的迁移库(RxJava2Interop )
2.操作符、背压、Scheduler、Hook以及结合Lambda
2.1 操作符
2.1.1 subscribeOn与ObserveOn
此处以subscribeOn为例
2.1.2 map、flatMap、switchMap、concatMap
此处以flatMap为例
涉及到的类图
flatMap:无法保证事件队列U是按序排列
试例:
private void testFlatMap(){
Log.d(TAG, "testFlatMap start");
Observable.just("A", "B", "C", "D", "E").flatMap(new Function<String, Observable<String>>() {
@Override
public Observable<String> apply(String s) throws Exception {
Log.d(TAG,"testFlatMap apply "+s);
return Observable.just(s + "1",s + "2").subscribeOn(Schedulers.newThread());
}
}).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onComplete() {
Log.d(TAG,"testFlatMap ------>onCompleted()");
}
@Override
public void onError(Throwable e) {
Log.d(TAG,"testFlatMap ------>onError()" + e);
}
@Override
public void onNext(String s) {
Log.d(TAG,"testFlatMap ------>onNext:" + s);
}
}/*s -> {Log.d(TAG,"testFlatMap ------>accept:" + s);int i = 1 / 0;} ,e -> Log.d(TAG,"testFlatMap ------>onError()" + e)*/);
Log.d(TAG, "testFlatMap end");
}
运行结果:
03-22 19:48:32.188 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap start
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap apply A
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap apply B
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap apply C
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap apply D
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap apply E
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap end
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onNext:A1
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onNext:A2
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onNext:B1
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onNext:B2
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onNext:D1
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onNext:D2
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onNext:E1
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onNext:E2
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onNext:C1
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onNext:C2
03-22 19:48:32.198 2092-2092/com.example.administrator.rxjavademo D/MainActivity: testFlatMap ------>onCompleted()
concatMap:可以保证按序
草图(非标准类图、非标准时序图,orz...)如下
试例:
同上 换成concatMap
运行结果:
03-22 19:55:31.658 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap start
03-22 19:55:31.668 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap apply A
03-22 19:55:31.668 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap end
03-22 19:55:31.668 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onNext:A1
03-22 19:55:31.668 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onNext:A2
03-22 19:55:31.668 10937-15859/com.example.administrator.rxjavademo D/MainActivity: testConcatMap apply B
03-22 19:55:31.668 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onNext:B1
03-22 19:55:31.668 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onNext:B2
03-22 19:55:31.668 10937-15860/com.example.administrator.rxjavademo D/MainActivity: testConcatMap apply C
03-22 19:55:31.668 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onNext:C1
03-22 19:55:31.668 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onNext:C2
03-22 19:55:31.668 10937-15861/com.example.administrator.rxjavademo D/MainActivity: testConcatMap apply D
03-22 19:55:31.668 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onNext:D1
03-22 19:55:31.668 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onNext:D2
03-22 19:55:31.668 10937-15862/com.example.administrator.rxjavademo D/MainActivity: testConcatMap apply E
03-22 19:55:31.678 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onNext:E1
03-22 19:55:31.678 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onNext:E2
03-22 19:55:31.678 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testConcatMap ------>onCompleted()
switchMap:旧的中间Observable<U>产生的事件序列没有发送完毕,在下一个中间的Observable开始发送后则停止对原事件序列订阅下发
草图(非标准类图、非标准时序图,orz...)如下
试例:
同上 换成switchMap
运行结果:
03-22 19:53:55.538 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testSwitchMap start
03-22 19:53:55.558 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testSwitchMap apply A
03-22 19:53:55.568 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testSwitchMap apply B
03-22 19:53:55.568 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testSwitchMap apply C
03-22 19:53:55.568 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testSwitchMap apply D
03-22 19:53:55.568 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testSwitchMap apply E
03-22 19:53:55.568 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testSwitchMap end
03-22 19:53:55.568 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testSwitchMap ------>onNext:E1
03-22 19:53:55.568 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testSwitchMap ------>onNext:E2
03-22 19:53:55.568 10937-10937/com.example.administrator.rxjavademo D/MainActivity: testSwitchMap ------>onCompleted()
2.2背压
场景:
当生产者生产事件过慢,消费者消费事件过快,消费者阻塞等待生产者,没有问题
当生产者生产事件过快,而消费者消费事件过慢的情况下,需要额外的缓存开销去容纳生产过剩的事件,而背压提供了异步场景下对生产者流速控制的策略
RxJava2.x中把支持背压的函数分离到Flowable类,Observable类中不支持背压
方式:
1.React pull mode
标准的RxJava是push mode,观察者Subscriber发起订阅后,事件流就从被观察者Flowable中生产并push过来,如何将push mode切换到pull mode的方法是Subscription的request方法
上图为网上copy的,下游文字写错,纠正下
//Flowable需要加主动request的,背压策略
private void testFlowable(){
Log.d(TAG,"testFlowable start");
// Flowable.range(1, 10)
// .subscribeOn(Schedulers.computation())
// .map(v -> v * v)
// .subscribe(i -> Log.d(TAG,"range onNext "+i));
List<Integer> list = new ArrayList<Integer>();
for(int i=0 ; i<10; i++){
list.add(i);
}
Flowable.fromIterable(list)
.subscribeOn(Schedulers.computation())
.subscribe(/*i -> Log.d(TAG,"fromIterable onNext "+i)*/
new Subscriber<Integer>() {
Subscription subcription;
@Override
public void onSubscribe(Subscription s) {
Log.d(TAG,"fromIterable onSubscribe "+s);
subcription = s;
subcription.request(1);//默认实现Long.MAX_VALUE
}
@Override
public void onNext(Integer integer) {
Log.d(TAG,"fromIterable onNext "+integer);
subcription.request(1);
}
@Override
public void onError(Throwable t) {
Log.d(TAG,"fromIterable onError "+t);
}
@Override
public void onComplete() {
Log.d(TAG,"fromIterable onComplete");
}
});
Log.d(TAG,"testFlowable end");
}
输出结果:
03-23 16:57:19.718 8740-8740/com.example.administrator.rxjavademo D/MainActivity: testFlowable start
03-23 16:57:19.758 8740-8740/com.example.administrator.rxjavademo D/MainActivity: fromIterable onSubscribe null
03-23 16:57:19.758 8740-8740/com.example.administrator.rxjavademo D/MainActivity: testFlowable end
03-23 16:57:19.758 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onNext 0
03-23 16:57:19.758 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onNext 1
03-23 16:57:19.758 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onNext 2
03-23 16:57:19.758 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onNext 3
03-23 16:57:19.758 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onNext 4
03-23 16:57:19.758 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onNext 5
03-23 16:57:19.758 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onNext 6
03-23 16:57:19.758 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onNext 7
03-23 16:57:19.758 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onNext 8
03-23 16:57:19.768 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onNext 9
03-23 16:57:19.768 8740-9904/com.example.administrator.rxjavademo D/MainActivity: fromIterable onComplete
2.丢弃sample、缓冲buffer window
3.onBackpresureBuffer、onBackPressureDrop
此处牵涉到两个概念
Hot Observable跟Cold Observable
Hot Observable指的是被观察者创建即开始生产事件发送,不等有观察者订阅才发送,如鼠标事件、股票价格 Observable.pulish()可以把cold observable转换为hot observable
Cold Observable指的是一般的被观察者等有观察者订阅才开始生产事件发送,interval range函数创建的都属于该类
总结:
背压只适用于异步场景,并不是说同步场景也需要用背压策略去流速控制
针对flowable事件发布速率过快的场景肯定需要加上request做背压
2.3 Scheduler
2.4 Hook
2.5 Lambada
3.android项目应用举例(结合retrofit)
3.1 先添加rxAndroid依赖(默认会自动引入对应的rxJava包)
dependencies {
compile"com.squareup.retrofit2:retrofit:$parent.ext.retrofitVersion"
compile"com.squareup.retrofit2:adapter-rxjava2:$parent.ext.retrofitVersion"
compile"com.squareup.retrofit2:converter-gson:$parent.ext.retrofitVersion"
compile"com.squareup.retrofit2:converter-scalars:$parent.ext.retrofitVersion"
compile"com.squareup.okhttp3:logging-interceptor:$parent.ext.okhttpVersion"
compile"io.reactivex.rxjava2:rxandroid:$parent.ext.rxAndroidVersion"
}
3.2 retrofit添加callAdapter适配业务接口方法返回类型为Observable
业务接口方法形如
@GET("{headUrl}")
Observable<String> getNewstockCount(
@Path(value ="headUrl",encoded =true) String url,
@QueryMapMap params);
此处Observable<String>一般使用会替换成Observable<T> T指的是接受通用返回body的bean类
rerotfit构造如下
public static Retrofit getRetrofitInstance(){
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).build();
return new Retrofit.Builder().baseUrl("XXX")
.addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync())
.addConverterFactory(ScalarsConverterFactory.create()).client(okHttpClient).build();
}
这里加粗的String一般实际运用根据业务需要指定接受相应body的bean类型
3.3直接使用返回的Observable进行subscribe做相应的链式处理
private void testRetrofit(){
Log.d(TAG, "testRetrofit start");
//结合retrofit使用
NetworkApi networkApi = RetrofitFactory.getRetrofitInstance().create(NetworkApi.class);
networkApi.getNewstockCount("XXXX",new HashMap<String,Object>()).subscribe(new Observer<String>(){
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onComplete() {
Log.d(TAG,"onCompleted");
}
@Override
public void onError(Throwable e) {
Log.d(TAG,"onError="+e.getLocalizedMessage());
}
@Override
public void onNext(String stringResponse) {
Log.d(TAG,"onNext="+stringResponse);
}
});
Log.d(TAG, "testRetrofit end");
}
4.相关开源库(RxBus、RxBinding、frodo、RxLifecycle)
5.优缺点
优点:
1.链式调用让用例流程清晰明了,某种程度上来说也是解耦,不再需要Handler 、new Thread
2.强大的数据变换功能以及线程切换,实际运用项目的时候可以插拔自己项目的线程池策略
缺点:
1.学习成本比较高,需要理解各种操作符,初期使用可能会有函数比较冗长的即视感
2.rxjava库升级带来的项目替换成本