Rxjava和Retrofit的使用

本文介绍如何在Android项目中集成Retrofit与RxJava2,实现网络请求的异步处理。通过添加依赖、创建Retrofit实例并配置拦截器,结合RxJava2进行响应式编程,提高应用性能。

添加依赖,最新的版本在github上查看。
implementation ‘com.squareup.okhttp3:okhttp:3.11.0’
implementation ‘com.squareup.okhttp3:logging-interceptor:3.11.0’
implementation ‘com.squareup.retrofit2:retrofit:2.4.0’
implementation ‘com.squareup.retrofit2:converter-gson:2.4.0’
implementation ‘com.squareup.retrofit2:converter-scalars:2.4.0’
implementation ‘com.squareup.retrofit2:adapter-rxjava2:2.4.0’ //进行支持rxjava2
implementation “io.reactivex.rxjava2:rxjava:2.2.2”
implementation ‘io.reactivex.rxjava2:rxandroid:2.1.0’

1.使用注解,进行标识接口和参数
在这里插入图片描述
2.需要创建Retrofit的对象,设置基地址,添加拦截器等
在这里插入图片描述
3.进行使用
在这里插入图片描述
使用rxjava2的形式
在这里插入图片描述

具体的demo:https://github.com/yunzheyue/rxjavaAndRetrofitTest

### RxJavaRetrofit使用方法 #### 依赖添加 若要使用RxJavaRetrofit,需在项目中添加相应依赖。如RetrofitRxJava结合使用时,可按如下方式添加依赖: ```groovy implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.okhttp3:okhttp:3.11.0' implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.squareup.retrofit2:converter-gson:2.0.2' implementation 'io.reactivex.rxjava2:rxandroid:2.0.2' implementation 'io.reactivex.rxjava2:rxjava:2.0.2' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' ``` 也可以按照Retrofit与RxAndroid结合使用的方式添加依赖: ```groovy compile 'io.reactivex:rxjava:1.1.6' compile 'io.reactivex:rxandroid:1.2.1' compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:retrofit-adapters:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' ``` #### Retrofit创建 在创建Retrofit时,可通过如下代码配置: ```java mRetrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(ScalarsConverterFactory.create())//增加返回值为String的支持 .addConverterFactory(GsonConverterFactory.create())//增加返回值为Gson的支持(以实体类返回) .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//增加返回值为Observable<T>的支持 .client(client) .build(); ``` ### RxJavaRetrofit结合使用案例 有一个展示RetrofitRxJava结合使用的Demo,不过为了清晰展示,该Demo未采用MVP构架,未用Dagger进行依赖注入,部分请求未在生命周期结束时取消,也没有UI的loading效果没网情况的处理等,实际使用时需根据需求处理[^1]。 ### RxJavaRetrofit结合使用的优势 RxJavaRetrofit结合可以利用RxJava强大的异步处理操作符功能,对Retrofit请求返回的数据进行灵活处理,使得代码更简洁、可维护性更高,能更方便地处理复杂的异步逻辑数据转换。同时,Retrofit本身具有简洁的API设计高效的网络请求能力,二者结合能提升开发效率代码质量。此外,网络上有很多介绍二者结合使用的优质文章,如某博客上的介绍文章:http://gank.io/post/560e15be2dca930e00da1083 ,以及优快云上的相关文章:http://blog.youkuaiyun.com/lzyzsd/article/details/41833541(一) 、http://blog.youkuaiyun.com/lzyzsd/article/details/44094895(二)等可供参考学习[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值