Android Rxjava+Retrofit网络请求框架 使用工具类优化

前言

借助泛型实现了复用,请求时可以比普通复用少写一点代码(滑稽脸),两种工具类都采用的单例模式

普通的工具类

因为必须知道具体的类型(url)才可以创建api的实体类,所以每增加一个url就要进来修改一次,即使只有一部分不同(在同一个接口中)也需要进来修改,非常僵硬麻烦,下面只贴了工具类


import android.util.Log;

import com.example.practice.api.ImageApi;
import com.example.practice.api.ServiceApi;
import com.example.practice.model.data.HomeData;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.example.practice.api.ServiceApi.DATA_HOME;

public class HttpManager {
    private static HttpManager instance;
//单例模式
    public static HttpManager getInstance() {
        if (instance == null) {
            synchronized (HttpManager.class) {
                if (instance == null) {
                    instance = new HttpManager();
                }
            }
        }
        return instance;
    }

    private ServiceApi homeApi;
    private String baseUrl = DATA_HOME;
    private ImageApi imageApi;
    private Map<String,Retrofit> map = new HashMap<>();
    private Retrofit getRetrofit(String url) {
        return new Retrofit.Builder().baseUrl(url)
                .client(getOKHttpClient())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private OkHttpClient getOKHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(new LoggingInterceptor())
                .build();
    }

    private class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Log.e("TAG", "intercept: 日志拦截器" );
            Response proceed = chain.proceed(request);
            Log.e("TAG", "intercept: 请求后" );
            return proceed;
        }
    }

    public ServiceApi getHomeApi() {
        if (homeApi == null) {
            homeApi = getRetrofit(baseUrl).create(ServiceApi.class);
        }
        return homeApi;
    }

    public ImageApi getImageApi(String baseUrl) {
        Retrofit retrofit = map.get(baseUrl);
        if(retrofit !=null){
            imageApi = retrofit.create(ImageApi.class);
        }else{
             retrofit = getRetrofit(baseUrl);
             imageApi = retrofit.create(ImageApi.class);
             map.put(baseUrl,retrofit);
        }
        return imageApi;
    }
}

使用泛型的工具类

因为普通的工具类是因为必须需要具体的类型才导致的僵硬,那么我们使用泛型让它变得不需要具体的类型就可以更灵活了,这里是配合MVP使用的。

工具类


public class RetrofitUtils implements INetWorkInterface {
    private static RetrofitUtils retrofitUtils;
    private ApiService apiService;

    private RetrofitUtils() {


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URLConstant.BASEURL)
                .client(getOKHttpClient())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        apiService = retrofit.create(ApiService.class);
    }
    private OkHttpClient getOKHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(new RetrofitUtils.LoggingInterceptor())
                .build();
    }

    private class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Log.e("TAG", "intercept: 日志拦截器");
            Response proceed = chain.proceed(request);
            Log.e("TAG", "intercept: 请求后");
            return proceed;
        }
    }

    public static RetrofitUtils getInstance() {
        if (retrofitUtils == null) {
            synchronized (RetrofitUtils.class) {
                if (retrofitUtils == null) {
                    retrofitUtils = new RetrofitUtils();
                }
            }
        }
        return retrofitUtils;
    }

    @Override
    public <T> void get(String url, INetCallBack<T> callBack) {
        apiService.get(url)
                .compose(RxUtils.changeScheduler())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResponseBody responseBody) {
                        try {
                            String string = responseBody.string();
                            Type[] genericInterfaces = callBack.getClass().getGenericInterfaces();
                            Type[] actualTypeArguments = ((ParameterizedType) genericInterfaces[0]).getActualTypeArguments();
                            Type t = actualTypeArguments[0];
                            T result = new Gson().fromJson(string, t);
                            callBack.onSuccess(result);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void one rror(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public <T> void post(String url, INetCallBack<T> callBack) {

    }

    @Override
    public <T> void post(String url, HashMap<String, String> map, INetCallBack<T> callBack) {

    }
}

工具类中使用到的接口和类

统一切换线程

public class RxUtils {

    /**
     * rxjava 线程切换统一处理
     *
     * @param <T>
     * @return
     */
    public static <T> FlowableTransformer<T, T> rxScheduler() {
        return new FlowableTransformer<T, T>() {
            @Override
            public Publisher<T> apply(Flowable<T> upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }


    public static <T> ObservableTransformer<T, T> changeScheduler() {
        return new ObservableTransformer<T, T>() {

            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }
}

使用的路径和retrofit接口

public interface URLConstant {
     String BASEURL = "http://cdwan.cn:7000/exam2003/";
   String BANNER = "abannerlist.json";
    String LEFT = "anewslist.json";
    String RIGHT = "astudent.json";
}

public interface ApiService {
    @GET
    Observable<ResponseBody> get(@Url String url);

    @FormUrlEncoded
    @POST
    Observable<ResponseBody> post(@Url String url);

    @FormUrlEncoded
    @POST
    Observable<ResponseBody> post(@Url String url, @FieldMap HashMap<String,String> map);
}

使用

        RetrofitUtils.getInstance().get(url, callBack);

上一篇:干货丨DolphinDB集群如何扩展节点和存储


下一篇:Swarm-bzz/Ipfs-fil的去中心化存储到底是什么?