当前位置: 代码迷 >> 综合 >> Rxjava2+Retrofit2网络请求
  详细解决方案

Rxjava2+Retrofit2网络请求

热度:69   发布时间:2023-12-22 15:14:51.0

 

前言

    Rxjava2这种通过观察者模式来处理异步问题,使得网络请求变得更容易,目前Rxjava2越来越火,也成为了不少框架用于异步处理的首选开源库。所以熟练掌握其基本用法也就成为了每个程序员应该具备的本领。

 

Gradle中添加依赖

    //Rxjavacompile 'io.reactivex.rxjava2:rxandroid:2.0.2'compile 'io.reactivex.rxjava2:rxjava:2.1.9'//网络请求compile 'com.squareup.retrofit2:retrofit:2.3.0' // retrofitcompile 'com.google.code.gson:gson:2.8.2' // gsoncompile 'com.squareup.retrofit2:converter-gson:2.2.0'compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'//RxJava2CallAdapterFactory适配器支持Rxjava2// compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2' RxJavaCallAdapterFactory适配器仅支持Rxjavacompile 'com.squareup.okhttp3:logging-interceptor:3.1.2'compile 'com.squareup.okhttp3:okhttp:3.10.0'

注意:如果使用RxJavaCallAdapterFactory适配器则有可能出现Unable to create call adapter for io.reactivex.Observable<okhttp3.ResponseBody>这个异常。

 

Retrofit2接口

public interface RequestServices {@GET//定义返回的方法,返回的响应体使用了ResponseBodyObservable<ResponseBody> getString(@Url String url);@FormUrlEncoded@POSTObservable<ResponseBody> post(@Url String url, @FieldMap Map<String, String> params);}

关于Retrofit2的使用Retrofit2网络请求详解可以查看这篇文章

 

初始化Retrofit对象

    在这里我只是对Retrofit做了简单处理,如果有需求可以查看一下okhttp+Retrofit的配合使用

OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();
//获取Retrofit对象,设置地址
retrofit = new Retrofit.Builder().baseUrl("http://localhost").client(OK_HTTP_CLIENT)//通过okhttp对retrofit进行加强.addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加Rxjava2适配器.build();

 

网络请求

    通过Retrofit对象创建出网络请求对象,通过该对象获取Observable对象,接下来就可以运用Rxjava的操作对数据进行处理

RequestServices requestServices = retrofit.create(RequestServices.class);Map<String, String> pamars1 = new HashMap<>();pamars1.put("key", "value");requestServices.post("请求url地址",pamars1)//这里我们即可获得一个Observable对象,这里我使用的是post请求.subscribeOn(Schedulers.io())//在io线程中做请求.observeOn(AndroidSchedulers.mainThread())//主线程显示数据.subscribe(new Observer<ResponseBody>() {@Overridepublic void onSubscribe(Disposable d) {}@Overridepublic void onNext(ResponseBody responseBody) {try {Log.d(TAG,responseBody.string());} catch (IOException e) {e.printStackTrace();}}@Overridepublic void onError(Throwable e) {}@Overridepublic void onComplete() {}});

 

 

合并多个网络请求

RequestServices requestServices = retrofit.create(RequestServices.class);Map<String, String> pamars1 = new HashMap<>();pamars1.put("key", "value");Map<String, String> pamars2 = new HashMap<>();pamars2.put("key", "value");requestServices.post("请求url地址",pamars1)//这里我们即可获得一个Observable对象.mergeWith(requestServices.post("请求url地址",pamars2))//合并两条网络请求.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())//主线程显示数据.subscribe(new Observer<ResponseBody>() {@Overridepublic void onSubscribe(Disposable d) {}@Overridepublic void onNext(ResponseBody responseBody) {try {Log.d(TAG,responseBody.string());} catch (IOException e) {e.printStackTrace();}}@Overridepublic void onError(Throwable e) {}@Overridepublic void onComplete() {}});

 

嵌套请求

 //嵌套请求requestServices.post("https://free-api.heweather.com/s6/weather?parameters",pamars1).flatMap(new Function<ResponseBody, ObservableSource<ResponseBody>>() {@Overridepublic ObservableSource<ResponseBody> apply(ResponseBody responseBody) throws Exception {Log.d(TAG,responseBody.string());return requestServices.post("https://free-api.heweather.com/s6/weather?parameters",pamars2);}}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())//主线程显示数据.subscribe(new Observer<ResponseBody>() {@Overridepublic void onSubscribe(Disposable d) {}@Overridepublic void onNext(ResponseBody responseBody) {try {Log.d(TAG,responseBody.string());} catch (IOException e) {e.printStackTrace();}}@Overridepublic void onError(Throwable e) {}@Overridepublic void onComplete() {}});

 

打包请求

//打包请求Observable.zip(requestServices.post("https://free-api.heweather.com/s6/weather?parameters", pamars1),requestServices.post("https://free-api.heweather.com/s6/weather?parameters", pamars2),new BiFunction<ResponseBody, ResponseBody, ResponseBody>() {@Overridepublic ResponseBody apply(ResponseBody responseBody, ResponseBody responseBody2) throws Exception {//这里可以合并两个数据然后返回 返回结果将传递到订阅信息中return null;}}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())//主线程显示数据.subscribe(new Observer<ResponseBody>() {@Overridepublic void onSubscribe(Disposable d) {}@Overridepublic void onNext(ResponseBody responseBody) {try {Log.d(TAG,responseBody.string());} catch (IOException e) {e.printStackTrace();}}@Overridepublic void onError(Throwable e) {}@Overridepublic void onComplete() {}});

 

源码地址 Rxjava2+Retrofit2网络请求Demo