编程语言
首页 > 编程语言> > Retrofit2中RxJava的使用

Retrofit2中RxJava的使用

作者:互联网

1.代码分析 

 

2.代码 

 OkHttpClient okHttpClient = new OkHttpClient();
        Retrofit retrofit = new Retrofit.Builder().baseUrl("www.xxxx.com")
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(buildGson()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
PersonalProtocol personalProtocol = retrofit.create(PersonalProtocol.class);
rx.Observable<PersonalInfo> observable  = personalProtocol.getPersonalListInfo(12);
      observable.subscribeOn(Schedulers.io()) 
                .observeOn(AndroidSchedulers.mainThread())//最后在主线程中执行
                .subscribe(new Subscriber<PersonalInfo>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void one rror(Throwable e) {
                        //请求失败
                    }

                    @Override
                    public void onNext(PersonalInfo personalInfo) {
                        //请求成功
                    }
                });
public interface PersonalProtocol {
    /**
     * 用户信息
     * @param page
     * @return
     */
    @FormUrlEncoded
    @POST("user/personal_list_info")
    Observable<PersonalInfo> getPersonalListInfo(@Field("cur_page") int page);
//    Call<Response<PersonalInfo>> getPersonalListInfo(@Field("cur_page") int page);
}
public static Gson buildGson() {
        Gson gson = new GsonBuilder()
                .serializeNulls()
                .registerTypeAdapter(int.class, new GsonIntegerDefaultAdapter())
                .create();
        return gson;
    }

public class GsonIntegerDefaultAdapter implements JsonSerializer<Integer>, JsonDeserializer<Integer> {
    @Override
    public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        try {
            if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定义为int类型,如果后台返回""或者null,则返回0
                return 0;
            }
        } catch (Exception ignore) {
        }
        try {
            return json.getAsInt();
        } catch (NumberFormatException e) {
            throw new JsonSyntaxException(e);
        }
    }

    @Override
    public JsonElement serialize(Integer src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src);
    }
}

 

标签:return,create,page,Override,使用,RxJava,new,Retrofit2,public
来源: https://blog.csdn.net/xie__jin__cheng/article/details/111329081