Retrofit结合RxJava使用说明

PS:年后一直没有更新博客,实在是太忙了。今天周六也是终于抽出了时间,就决定写一篇Retrofit结合RxJava使用说明。刚好现在写的的项目中也有用到,趁热打铁简单说说。最近也不知道博客写什么内容,大家有什么想了解的内容,也可以评论告诉我,我尽力解答。

如果对Retrofit不了解可以看我之前的一篇博客:Retrofit 2.0使用 ,这次的内容也是在此基础上的。关于RxJava可以参考:学习RxJava(资料汇总),这里我就不多说了。

1.准备工作

我们需要添加相应的依赖:

    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'

2.使用

首先我在网上随便找了一个接口用于测试:http://apistore.baidu.com/microservice/cityinfo?,Get请求,参数是cityname也就是你要查询的城市名称。我以查询西安为例。

我们首先直接请求看一下返回结果:

{
    "errNum": 0,
    "retMsg": "success",
    "retData": { "cityName": "西安", "provinceName": "陕西", "cityCode": "101110101", "zipCode": "710000", "telAreaCode": "029" } }

那么我们先写一个City对象用于Gson解析(这里我们只获取retData中的数据,后面我会用自定义转换器转换):

public class City {

    private String cityName;
    private String provinceName;
    private String cityCode;
    private String zipCode;
    private String telAreaCode;

    public City(String cityName, String provinceName, String cityCode, String zipCode, String telAreaCode) {
        this.cityName = cityName;
        this.provinceName = provinceName;
        this.cityCode = cityCode;
        this.zipCode = zipCode;
        this.telAreaCode = telAreaCode;
    }

    public String getProvinceName() {
        return provinceName;
    }

    public void setProvinceName(String provinceName) {
        this.provinceName = provinceName;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getZipCode() {
        return zipCode;
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }

    public String getTelAreaCode() {
        return telAreaCode;
    }

    public void setTelAreaCode(String telAreaCode) {
        this.telAreaCode = telAreaCode;
    }
}

Api请求接口:

public interface CityApi {

    @GET("cityinfo?")
    Observable<City> getCityInfo(@Query("cityname") String cityname);

}

自定义转换器:

public class DeserializerCity <T> implements JsonDeserializer<T> {
    @Override
    public T deserialize(JsonElement je, Type typeOfT,
                               JsonDeserializationContext context) throws JsonParseException {
        // 转换Json的数据
        JsonElement results = je.getAsJsonObject().get("retData");
        return new Gson().fromJson(results, typeOfT);
    }
}

创建CityApi类:

    public class CityService {

    public static final String CITY_URL = "http://apistore.baidu.com/microservice/";

    private static Gson customGsonInstance = new GsonBuilder()
            .registerTypeAdapter(City.class,new DeserializerCity<City>())
            .create();

    private static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(CITY_URL)
            .addConverterFactory(GsonConverterFactory.create(customGsonInstance))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

    public static CityApi createCityService() {
        return retrofit.create(CityApi.class);
    }

}

调用:

public void getCityInfo(String cityname){
    CityApi service = CityService.createCityService();
    Subscription subscription = service.getCityInfo(cityname)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .unsubscribeOn(Schedulers.io())
                    .subscribe(new Subscriber<City>() {
                        @Override
                        public void onCompleted() {

                        }
                        @Override
                        public void onError(Throwable error) {

                        }
                        @Override
                        public void onNext(City city) {
                            Log.d("CityInfo:",city.getCityCode() + "--" + city.getProvinceName());
                        }
                    });

    }

结果:

D/CityInfo:: 101110101--陕西

以上就是简单的使用方法。觉得好的多多点赞!

你可能感兴趣的:(retrofit,rxjava)