您的位置:首页 > 编程语言 > Java开发

Retrofit和RxJava结合使用

2016-09-30 16:12 483 查看
Retrofit和RxJava系列博客:

使用Retrofit上传文件

使用Gson解析Retrofit返回结果

Retrofit和RxJava结合使用

使用Retrofit和RxJava进行轮询操作

使用Retrofit的时候就不得不提到RxJava,RxJava是一个基于观察者模式的异步实现。关于RxJava的入门学习,强烈推荐《给Android开发者的RxJava详解》

https://gank.io/post/560e15be2dca930e00da1083

正如上篇博客所说,得益于Retrofit中灵活的
Converter
,所以Retrofit对RxJava的支持也是异常的方便。我个人的感觉是,虽然RxJava的学习曲线比较陡峭,但是一旦学会,编程效率将大大提高。如果使用Retrofit而不用RxJava是非常可惜的,本文将阐述如何将Retrofit和RxJava进行结合。。

添加依赖

首先在build.gradle中加入依赖。为了使用gson解析json,还需要加入
gson
converter-gson
两个依赖,为了支持RxJava,还需要加入
rxjava
rxandroid
的库,而衔接RxJava和Retrofit的就是
adapter-rxjava
这个库。

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.5'


定义请求接口

和之前的定义一样,为了使用RxJava,需要把返回值改成
Observable
类型即可:

public interface RetrofitImageUploadService {
@Multipart
@POST("EntranceGuardes/app/appOpen_pushdDataToApp.action")
Observable<UploadJsonResult> upload(@Part("userId") RequestBody description,
@Part MultipartBody.Part file);
}


这样,
upload
方法的返回值就是
Observable<UploadJsonResult>
类型,可以想象到,这样的返回值很容易和RxJava的数据流结合起来。

添加adapter-rxjava

和添加Gson支持一样,只需要在Retrofit对象中加入
addCallAdapterFactory
即可。
addCallAdapterFactory(RxJavaCallAdapterFactory.create())
就可以使用
RxJavaCallAdapterFactory
把Retrofit和RxJava结合起来。

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://172.18.81.155:8080/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();

RetrofitImageUploadService service = retrofit.create(RetrofitImageUploadService.class);


进行网络请求

这时调用service的upload方法,返回的结果就是
Observable<UploadJsonResult>
,这样就很容易与RxJava中丰富的运算符结合起来,方便各种处理。

Observable<UploadJsonResult> r=service.upload(description, body)


使用RxJava运算符

从上一步得到了
Observable
类型的对象,我们如果需要对返回结果进行一些处理,只需要使用RxJava中的丰富的运算符就可以了。而RxJava中有对lambda表达式的支持,只要使用Java SE8就可以使用lambda表达式来简写其中的运算符。

service.upload(description, body)
.doOnNext(uploadJsonResult -> Log.d("upload image", uploadJsonResult.getMessage()))
.doOnError(throwable -> Log.d("upload image", "upload failed"));


上面两句运算符使用了lambda表达式。
doOnNext
表示如果请求成功,将在日志中打印出
uploadJsonResult.getMessage()
中得到的数据。
doOnError
表示如果请求失败,将在日志中打印”upload failed”。除此之外,我们还可以增加线程的切换,比如使用
observeOn(Schedulers)
让网络请求在io线程中执行。

完整代码

public class UpLoadImage {
public interface RetrofitImageUploadService { @Multipart @POST("EntranceGuardes/app/appOpen_pushdDataToApp.action") Observable<UploadJsonResult> upload(@Part("userId") RequestBody description, @Part MultipartBody.Part file); }

private String imagePath;
private String userId;

public UpLoadImage(String userId, String imagePath) {
this.imagePath = imagePath;
this.userId = userId;
}

public Observable<UploadJsonResult> upload() {
File file = new File(imagePath);

Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://172.18.81.155:8080/") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); RetrofitImageUploadService service = retrofit.create(RetrofitImageUploadService.class);

RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

RequestBody description = RequestBody.create(MediaType.parse("text/plain"), userId);

return service.upload(description, body) .doOnNext(uploadJsonResult -> Log.d("upload image", uploadJsonResult.getMessage())) .doOnError(throwable -> Log.d("upload image", "upload failed"));

}
}


代码地址

https://github.com/flyingzhao/RxJavaPolling/blob/master/app/src/main/java/com/optimais/pollingtest/UpLoadImage.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息