简单的Retrofit+Rxjava二次封装

Retrofit是一个常用的网络请求框架。他的底层实现也是用OkHttp,只不过比OkHttp代码少实现的更能一样。使用Get或者Post都是用注解的方式来实现。

想要实现Retrofit+Rxjava需要导入依赖:

compile 'com.squareup.retrofit2:retrofit:2.3.0'   、

compile 'com.squareup.retrofit2:converter-gson:2.3.0'

compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.7'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'

这就是需要导入的依赖

下面的代码就是二次封装

 
public class RetrofitHelper {
    public static OkHttpClient okHttpClient;
    public static ServiceApi serviceApi;
    static {
    initOkhttpClient();
    }
    //单利模式
    private static void initOkhttpClient(){
        if (okHttpClient==null){
            synchronized (RetrofitHelper.class){
                if (okHttpClient==null){
                    okHttpClient=new OkHttpClient.Builder()
                            .build();
                }
            }
        }
    }
    //定义一个泛型
    public static  T createAPI(Class tClass,String url){
        Retrofit retrofit= new Retrofit.Builder()
                .baseUrl(url)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(tClass);
    }
    public static ServiceApi getShopAPI(){
        if (serviceApi==null){
            synchronized (RetrofitHelper.class){
                if (serviceApi==null){
                    serviceApi=createAPI(ServiceApi.class, Constants.BASE_URL);
                }
            }
        }
        return serviceApi;
    }
}

你可能感兴趣的:(简单的Retrofit+Rxjava二次封装)