[置顶] Android-->Rxjava与Retrofit2的结合实战

阅读之前,请先了解:
RxJava/RxAndroid 入门初体验
Android–>Retrofit 2.0 beta2 使用方法

本文使用的版本信息:
compile ‘io.reactivex:rxjava:1.1.2’
compile ‘io.reactivex:rxandroid:1.1.0’
compile ‘com.squareup.retrofit2:retrofit:2.0.0’
compile ‘com.squareup.retrofit2:converter-gson:2.0.0’
compile ‘com.squareup.retrofit2:adapter-rxjava:2.0.0’

文章之前,需要有一个后台接口,并且可以返回数据:
假设接口是: http://192.168.1.12:8082/api
返回数据是:

{
    rid: 12,
    name_char: "马化腾",
    name_varchar: "埃里巴巴",
    name_float: 0,
    name_int: 0,
    name_tinyint: 0,
    name_time: 1478833860000,
    param: {
        pp1: "2",
        basd: "0123adf"
    }
} //param:这个字段是传入的参数,封装成的json数据,又返回回来的.主要用于测试参数传递是否正确

有了接口,有了接口数据,就可以开始写Android代码了:

1:创建一个专门用于调用API服务的类

//public static String BASE_URL = "http://192.168.1.12:8082";//注意这个服务器地址
public interface RApiService {

    /** * @GET 表明方法是 get请求 * "/api" 请求的接口,请注意前面的/符号 * @Query 表示这是一个参数 * Call<ResponseBody> :Call是必须的,ResponseBody是Retrofit默认的返回数据类型,也就是String体 */

    @GET("/api")
    Call<ResponseBean> getApi(@Query("pa1") String va1, @Query("ba1") String va2);
    //getApi方法,等效于: http://192.168.1.12:8082/api?pa1=va1&ba1=va2


    /** * @POST 请求方式post * @Body 表示将requestBean对象转成成json string作为参数传递给后台 */
    @POST("/api")
    Call<ResponseBean> postApi(@Body RequestBean requestBean);


    /** * @QueryMap 表示将map类型的params对象,转成键值对的形式作为参数传递给后台 */
    @GET("/api")
    Call<ResponseBody> getApiString(@QueryMap Map<String, String> params);

    @POST("/api")
    Call<ResponseBody> postApiString(@Body RequestBean requestBean);

    /** * Observable 是RxJava的关键点,其他不变 */
    @GET("/api")
    Observable<ResponseBody> getRxApiString(@QueryMap Map<String, String> params);

    @POST("/api")
    Observable<ResponseBean> postRxApiString(@Body RequestBean requestBean);
}

接口声明完之后, 就可以开始条用了.

2.创建Retrofit对象

//这是我封装的类,可以复制粘贴直接使用
public class RRetrofit {
    public static String BASE_URL = "http://192.168.1.12:8082";
    public static <T> T create(final Class<T> cls) {
        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder
           .baseUrl(BASE_URL)//注意此处,设置服务器的地址
           .addConverterFactory(GsonConverterFactory.create())//用于Json数据的转换,非必须
           .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//用于返回Rxjava调用,非必须
           .build();
        return retrofit.create(cls);
    }
}
注意:
GsonConverterFactory.create(), 需要compile 'com.squareup.retrofit2:converter-gson:2.0.0'
RxJavaCallAdapterFactory.create(),需要 compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'

3.调用接口

public void button(View view) {
RApiService service = RRetrofit.create(RApiService.class);

/*get请求*/
Call<RApiService.ResponseBean> api = service.getApi("pa1_value", "ba1_value");
api.enqueue(new Callback<RApiService.ResponseBean>() {
 @Override
 public void onResponse(Call<RApiService.ResponseBean> call, Response<RApiService.ResponseBean> response) {
     append("getApi-->\n" + response.body().toString());
 }

 @Override
 public void onFailure(Call<RApiService.ResponseBean> call, Throwable t) {
     Log.e("", "");
     append("getApi error-->\n" + t.toString());
 }
});

Map<String, String> params = new HashMap<>();
params.put("bbb", "bbb_v");
params.put("aaa", "aaa_v");
Call<ResponseBody> apiString = service.getApiString(params);
apiString.enqueue(new Callback<ResponseBody>() {
 @Override
 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
     Log.e("", "");
     try {
         append("getApiString-->\n" + response.body().string());
     } catch (IOException e) {
         e.printStackTrace();
     }
 }

 @Override
 public void onFailure(Call<ResponseBody> call, Throwable t) {
     Log.e("", "");
     append("getApiString error-->\n" + t.toString());
 }
});



/*post请求*/
RApiService.RequestBean requestBean = new RApiService.RequestBean();
requestBean.key1 = "KEY1";
requestBean.key2 = "KEY2";
requestBean.key3 = "KEY3";
requestBean.key4 = "KEY4";
Call<RApiService.ResponseBean> postApi = service.postApi(requestBean);
postApi.enqueue(new Callback<RApiService.ResponseBean>() {
 @Override
 public void onResponse(Call<RApiService.ResponseBean> call, Response<RApiService.ResponseBean> response) {
     Log.e("", "");
     append("postApi-->\n" + response.body().toString());
 }

 @Override
 public void onFailure(Call<RApiService.ResponseBean> call, Throwable t) {
     Log.e("", "");
     append("postApi error-->\n" + t.toString());
 }
});

Call<ResponseBody> postApiString = service.postApiString(requestBean);
postApiString.enqueue(new Callback<ResponseBody>() {
 @Override
 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
     Log.e("", "");
     try {
         append("postApiString-->\n" + response.body().string());
     } catch (IOException e) {
         e.printStackTrace();
     }
 }

 @Override
 public void onFailure(Call<ResponseBody> call, Throwable t) {
     Log.e("", "");
     append("postApiString error-->\n" + t.getMessage());
 }
});

/*rx的使用*/
service.getRxApiString(params)
     .subscribeOn(Schedulers.newThread())
     .observeOn(AndroidSchedulers.mainThread())
     .subscribe(new Subscriber<ResponseBody>() {
         @Override
         public void onCompleted() {
             append("getRxApiString onCompleted-->\n");
         }

         @Override
         public void onError(Throwable e) {
             append("getRxApiString onError-->\n" + e.getMessage());
         }

         @Override
         public void onNext(ResponseBody responseBody) {
             try {
                 append("getRxApiString onNext-->\n" + responseBody.string());
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     });
service.postRxApiString(requestBean).subscribeOn(Schedulers.newThread())
     .observeOn(AndroidSchedulers.mainThread())
     .subscribe(new Subscriber<RApiService.ResponseBean>() {
         @Override
         public void onCompleted() {
             append("postRxApiString onCompleted-->\n");
         }

         @Override
         public void onError(Throwable e) {
             append("postRxApiString onError-->\n" + e.getMessage());
         }

         @Override
         public void onNext(RApiService.ResponseBean responseBody) {
             append("postRxApiString onNext-->\n" + responseBody.toString());
         }
     });
}

以上就是调用方式.

至此: 文章就结束了,如有疑问: QQ群:274306954 欢迎您的加入.

你可能感兴趣的:(android,rxjava,rxandroid,Retrofit-2)