RxJava+Retrofit 简单的封装及应用

添加依赖:

implementation 'cn.finalteam:okhttpfinal:2.0.7'
implementation 'io.reactivex.rxjava2:rxjava:2.1.8' //rxjava
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'  //rxandroid 线程调度
implementation 'io.reactivex:rxandroid:1.1.0'  //rxandroid 线程调度
implementation 'com.squareup.retrofit2:retrofit:2.1.0' //retrofit2.0
implementation 'com.squareup.retrofit2:converter-gson:2.1.0' //ConverterFactory的Gson:
implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

整理接口(POST  GET等请求):

//关于参数请自行百度

public interface HttpService {

    @POST("url")
    Observable<BaseBean<ArticleInfo>> getCarousel();

    @GET("url")
    Observable<GetCodeBean> getAuthCode();
}

创建HttpManage,设置超时时间添加拦截器,添加请求结果转换类并适配RxJava:

public class HttpManage {
    private static HttpService httpService;
    public static String a ;
    private static final int DEFAULT_TIME_OUT = 5;//超时时间 5s
    private static final int DEFAULT_READ_TIME_OUT = 10;
    public static HttpService getServer(){

        if (httpService==null){
            synchronized (HttpManage.class){
                if (httpService==null){

                    // 创建 OKHttpClient
                    OkHttpClient.Builder builder = new OkHttpClient.Builder();
                    builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);//连接超时时间        builder.writeTimeout(DEFAULT_READ_TIME_OUT,TimeUnit.SECONDS);//写操作 超时时间
                    builder.readTimeout(DEFAULT_READ_TIME_OUT,TimeUnit.SECONDS);//读操作超时时间
                    Retrofit retrofit=new Retrofit.Builder()//创建Retrofit的实例
                            .client(builder.build())
                            .baseUrl(ApiConfig.BASE_URL)
                            .addConverterFactory(MvpGsonConverterFactory.create())  //请求结果转换成实体类
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //适配Rxjava
                            .build();
                    httpService=retrofit.create(HttpService.class);          //获得接口的实例

                }
            }
        }
        return httpService;
    }
}

编写MyHttps类,添加Loading:

public class MyHttps extends ObjectLoader {

    private Context context;
    public MyHttps(Context context) {
        this.context = context;
    }
    private Dialog mDialog;

    public Observable<BaseBean<ArticleInfo>> getCodeBeanObservable(){
        mDialog = new ProgressDialog(context);
        mDialog.setTitle("数据获取中。。。");
        return observe(HttpManage.getServer().getCarousel())
                .doOnSubscribe(()->mDialog.show())
                .doOnCompleted(()->mDialog.dismiss())
                .map(new Func1<BaseBean<ArticleInfo>, BaseBean<ArticleInfo>>() {
                    @Override
                    public BaseBean<ArticleInfo> call(BaseBean<ArticleInfo> dataBean) {
                        mDialog.dismiss();
                        return dataBean;
                    }
                });
    }
}

ObjectLoader:

public class ObjectLoader {
    /**
     *
     * @param observable
     * @param <T>
     * @return
     */
    protected  <T> Observable<T> observe(Observable<T> observable){
        return observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
}

重写Gson转换类:

public class MvpGsonConverterFactory  extends Converter.Factory {
    /**
     * Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and
     * decoding from JSON (when no charset is specified by a header) will use UTF-8.
     */
    public static MvpGsonConverterFactory create() {
        return create(new Gson());
    }

    /**
     * Create an instance using {@code gson} for conversion. Encoding to JSON and
     * decoding from JSON (when no charset is specified by a header) will use UTF-8.
     */
    @SuppressWarnings("ConstantConditions") // Guarding public API nullability.
    public static MvpGsonConverterFactory create(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        return new MvpGsonConverterFactory(gson);
    }

    private final Gson gson;

    private MvpGsonConverterFactory(Gson gson) {
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new MvpGsonResponseBodyConverter<>(gson, adapter,type);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new MvpGsonRequestBodyConverter(gson, adapter);
    }
}

 

public class MvpGsonRequestBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    MvpGsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override public T convert(ResponseBody value) throws IOException {
        JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try {
            T result = adapter.read(jsonReader);
            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
            return result;
        } finally {
            value.close();
        }
    }
}
public class MvpGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    //增加了type类型
    private Type type;

    MvpGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter,Type type) {
        this.gson = gson;
        this.adapter = adapter;
        this.type = type;
    }

    @Override public T convert(ResponseBody value) throws IOException {
        if (type == String.class) {
            try {
                MediaType mediaType = value.contentType();
                Charset charset = null;
                if (mediaType == null) {
                    charset = mediaType.charset();
                }
                String s = new String(value.bytes(), charset == null ? StandardCharsets.UTF_8 : charset);
                return (T) s;
            } finally {
                value.close();
            }
        } else {
            JsonReader jsonReader = gson.newJsonReader(value.charStream());
            try {
                T result = adapter.read(jsonReader);
                if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                    throw new JsonIOException("JSON document was not fully consumed.");
                }
                return result;
            } finally {
                value.close();
            }
        }
    }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值