Use Retrofit in combination with RxJava instructions

Source: Internet
Author: User

Use Retrofit in combination with RxJava instructions

PS: I haven't updated my blog after years. It's so busy. Today, Saturday finally took time out and decided to write an article about using Retrofit with RxJava. It is also useful for the projects I have just written. I do not know what the blog has written recently. If you want to know anything about it, you can also comment on it and tell me, I will try my best to answer it.

If you do not know about Retrofit, you can refer to my previous blog: Using Retrofit 2.0. This article is based on this. For details about RxJava, refer to: Learn RxJava (Data Summary). I will not talk about it here.

1. Preparations

We need to add the corresponding dependency:

    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. Use

First, I found an interface on the Internet for testing: http://apistore.baidu.com/microservice/cityinfo ?, Get request. The parameter iscitynameThat is, the name of the city you want to query. Take Xi'an as an example.

First, let's directly request to see the returned results:

{"ErrNum": 0, "retMsg": "success", "retData": {"cityName": "Xi'an", "provinceName": "Shaanxi", "cityCode ": "101110101", "zipCode": "710000", "telAreaCode": "029 "}}

First, we need to write a City object for Gson resolution (Here we only get the data in retData, and I will use the custom converter to convert it later ):

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 request interface:

public interface CityApi {    @GET("cityinfo?")    Observable
  
    getCityInfo(@Query("cityname") String cityname);}
  

Custom converter:

Public class DeserializerCity
  
   
Implements JsonDeserializer
   
    
{@ Override public T deserialize (JsonElement je, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {// JsonElement results = je. getAsJsonObject (). get ("retData"); return new Gson (). fromJson (results, typeOfT );}}
   
  

Create a CityApi class:

    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
  
   ())            .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);    }}
  

Call:

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
  
   () {                        @Override                        public void onCompleted() {                        }                        @Override                        public void onError(Throwable error) {                        }                        @Override                        public void onNext(City city) {                            Log.d("CityInfo:",city.getCityCode() + "--" + city.getProvinceName());                        }                    });    }
  

Result:

D/CityInfo: 101110101 -- Shaanxi

The above is a simple method of use. I think it's better!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.