1.添加依赖:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'io.reactivex.rxjava2:rxjava:2.1.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
RxJava与Retrofit一起使用,除了基础库之外,要注意第四个,Retrofit的adapter,添加完成之后就可以使用了。
2.使用Retrofit
回顾一下Retrofit的使用方法,下面是一个获取并显示网络图片的例子:
首先定义访问接口,这里要获取的是图片,需要Stream数据,所以直接使用ResponseBody作为泛型参数:
public interface ConnectService {
@Streaming
@GET("IC.png")
Call<ResponseBody> getImage();
}
然后创建Retrofit对象,访问网络,获取ResponseBody并进行处理:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.101:8080/")
//必须指定一个converter,否则报错,实际上并没有用到
.addConverterFactory(GsonConverterFactory.create())
.build();
ConnectService cs = retrofit.create(ConnectService.class);
final Call<ResponseBody> imageCall = cs.getImage();
//开始异步访问
imageCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//从Response获取inputstream
InputStream inputStream = response.body().byteStream();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//获取到图片,设置到imageView
runOnUiThread(new Runnable() {
@Override
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
}
3.与RxJava配合使用
第一步同样是定义访问接口,这里的类型不再是Call,而是被观察者Observable:
public interface ImageService {
@Streaming
@GET("IC.png")
Observable<ResponseBody> getImg();
}
接下来的步骤也基本一样,需要注意的是,构建Retrofit对象时要指定callAdapter:
//构建Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("192.168.1.101:8080/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
//获取网络访问接口实例
ImageService is = retrofit.create(ImageService.class);
//构建被观察者Observable
Observable<ResponseBody> observable = is.getImg();
//订阅。订阅之后自动执行网络访问。
observable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull ResponseBody responseBody) {
//获取ResponseBody并设置到imageview
mImgView.setImageBitmap(BitmapFactory.decodeStream(responseBody.byteStream()));
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
或者可以采用更简洁的写法:
new Retrofit.Builder()
.baseUrl("http://192.168.1.101:8080/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(ImageService.class)
.getImg()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<ResponseBody>() {
@Override
public void accept(@NonNull ResponseBody responseBody) throws Exception {
mImgView.setImageBitmap(BitmapFactory.decodeStream(responseBody.byteStream()));
}
});