Android Retrofit2.0+RxJava3.0 基本使用

一,ReactiveX

要学习RxJava,那么不得不提他的由来ReactiveX,ReactiveX 是一个专注于异步编程与控制可观察数据(或者事件)流的API。它组合了观察者模式,迭代器模式和函数式编程的优秀思想。ReactiveX是Reactive Extensions的缩写,一般简写为Rx,最初是LINQ的一个扩展,由微软的架构师Erik Meijer领导的团队开发;

二,Rx的发展

Rx这几年非常流行,以至于开发出多种语言版本,例如RxJava 、 RxGo 、RxJS、RxKotlin、RxPYRx.NET等等;Rx的大部分语言库由ReactiveX这个组织负责维护,社区网站是 reactivex.io

三,RxJava

RxJava是响应式编程(Reactive Extensions)的java实现,它基于观察者模式的实现了异步编程接口。

Rxjava 3.x 的github官网

Rxjava 3.0的一些改变:官方Wiki

Rxjava 3.x 文档可以在官方javadoc中找到

1,Retrofit + RxJava3组合使用

首先要引入依赖

    implementation "io.reactivex.rxjava3:rxjava:3.0.0"
    implementation 'io.reactivex:rxandroid:1.2.1'
    implementation 'com.squareup.retrofit2:retrofit:2.7.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'

相关配置module下的build.gradle

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

注意Retrofit和RxJava组合使用时,Retrofit中使用的rxjava适配器(adapter-rxjava3)要和RxJava版本(io.reactivex.rxjava3:rxjava:3.0.0)一致;如本例都是使用的时3.0;关于先前Rerotfit没有Rxjava3.0适配器问题;

创建Retrofit时如果要使用rxjava适配,注意不要写错,正确姿势如下代码:

Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
                // Or
                // .addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(Schedulers.io()))
                .baseUrl("")
                .build();

2,Retrofit + RxJava组合使用

如果要使用1.0可以这样添加依赖

 implementation 'io.reactivex:rxjava:1.0.14
 implementation 'io.reactivex:rxandroid:1.0.1'
 implementation 'com.squareup.retrofit2:retrofit:2.0.2'
 implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

Retrofit创建的正确姿势:

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://www.baidu.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

3,Retrofit + RxJava2.0组合使用

关于RxJava2.0的使用要从一个异常说起:

异常:

Could not locate call adapter for io.reactivex.Observable<okhttp3.ResponseBody>.

compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0' RxJava适配器是1.0

所以换成RxJava2.0就可以了,原因Android项目中使用的是RxJava2.0,那么Retrofit要配合Rxjava使用,相应的要配置Rxjava2.0适配器;以此类推如果要使用Rxjava3.0那么相应的Retrofit中的

两种方式配置Retrofit中使用的RxJava2.0适配器

1,第三方的提供的RxJava2.0适配器

implementation  'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

2,从Retrofit 2.2.0版开始,RxJava2有一个官方提供的适配器:

implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(new OkHttpClient.Builder().build())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
return retrofit.create(serviceClass);

四,Retrofit+Rxjava2具体使用案例

Retrofit+Rxjava2实现图片批量下载的功能

猜你喜欢

转载自blog.csdn.net/ezconn/article/details/109224878