Android-Rxjava&retrofit&dagger

Android网络请求Retrofit2+Rxjava2+Okh

2018-05-24  本文已影响93人  ruancw

前言:Retrofit2+Rxjava2+Okhttp3的网络请求框架无疑是当前最流行的网络请求方式,retrofit负责请求的数据结果,rxjava负责线程间的调度,okhttp负责数据请求的过程,Retrofit2+Rxjava2+Okhttp3三者完美的切合使得其功能更加强大,简单记录下在项目中使用时的简单封装。

1.导入依赖

implementation 'io.reactivex.rxjava2:rxjava:2.1.13'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'

2.ApiService接口

/**
 * Created by ruancw on 2018/5/22.
 * 数据请求接口
 */

public interface ApiService {
    //获取数据
    @FormUrlEncoded
    @POST
    Observable<HttpResponse> getRemoteData(@Url String url, @FieldMap LinkedHashMap<String, String> map);

    //上传文件
    @Multipart
    @FormUrlEncoded
    @POST
    Observable<HttpResponse> upLoadFile(@Url String url, @Part List<MultipartBody.Part> file, @FieldMap LinkedHashMap<String, String> map);
  //文件下载
    @Streaming
    @GET
    Observable<ResponseBody> downloadFile(@Url() String url);
}

HttpResponse通用数据返回类:

/**
 * Created by ruancw on 2018/5/23.
 * 网络请求数据返回类
 */

public class HttpResponse<T> {
    private String message;
    private int status;
    private T data;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

}

3.HttpApiService网络请求类

(1)单例模式创建retrofit

private Retrofit retrofit;

public static HttpApiService getInstance() {
    return Singleton.instance;
}

private static class Singleton {
    private static HttpApiService instance = new HttpApiService();
}

private HttpApiService(){
    retrofit = new Retrofit.Builder()
            .baseUrl(ApiConstant.baseUrl)//基础url
            .addConverterFactory(GsonConverterFactory.create())//将返回的数据转为Gson
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加Rxjava的回调
            .client(genericClient())//添加okHttpClient
            .build();
}

(2)创建okhttpClient

private OkHttpClient genericClient() {
    OkHttpClient httpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {//添加拦截器,可进行其他相关操作
                    Request request=chain.request();
                    request=request
                            .newBuilder()
                            .build();
                    return chain.proceed(request);
                }
            })
            //okHttpClient log日志打印
            .addInterceptor(new HttpLoggingInterceptor()
                    .setLevel(HttpLoggingInterceptor.Level.BODY))
            .build();
    return httpClient;
}

(3)获取apiService实例

//通过retrofit获取ApiService实例
private ApiService getApiService() {
    return getService(ApiService.class);
}

private <T> T getService(Class<T> cls) {
    return retrofit.create(cls);
}

(4)定义接口调用方法

//获取网络数据
public  Observable getRemoteData(String url, LinkedHashMap<String, String> map) {
    return getApiService().getRemoteData(url,map);
}
//上传文件
public  Observable updateFile(String url, List<MultipartBody.Part> file, LinkedHashMap<String, String> map) {
    return getApiService().upLoadFile(url,file,map);
}

//下载文件
public  Observable downloadFile(String url) {
    return getApiService().downloadFile(url);
}

4.定义Rxjava的注册与反注册方法

/**
 * rxjava取消注册
 */
public void unSubscribe(){
    if (mCompositeDisposable != null) {
        mCompositeDisposable.dispose();
    }
}

/**
 * rxjava进行注册
 * @param disposable
 */

public void addSubscription(Disposable disposable) {//rxjava进行注册
    if (mCompositeDisposable == null) {
        mCompositeDisposable= new CompositeDisposable();
    }
    mCompositeDisposable.add(disposable);
}

5.presenter实体类中调用

(1)定义Disposable通用类(RxJava2中新的名称)

/**
 * 
 * @param observable 被观察者
 * @param which 用于区分来自哪个请求
 * @param onRequestListener 请求响应接口
 * @param <T> data的数据类型
 * @return Disposable
 */
public  static  <T> Disposable getDisposable(Observable<HttpResponse<T>> observable, final String which, final IBaseModel.IOnRequestListener onRequestListener) {
    Disposable disposable=observable
            .subscribeOn(Schedulers.io())//子线程
            .observeOn(AndroidSchedulers.mainThread())//主线程
            .subscribe(new Consumer<HttpResponse<T>>() {
                @Override
                public void accept(HttpResponse<T> tHttpResponse) throws Exception {
                    if (onRequestListener!=null&&tHttpResponse!=null){
                        onRequestListener.onRequestSuccess(tHttpResponse,which);
                    }
                }

            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    if (onRequestListener!=null){
                        ExceptionHandle.handleException(throwable);
                        throwable.printStackTrace();
                        onRequestListener.onRequestFail(throwable);
                    }
                }
            });
    return disposable;
}

(2)model中获取Disposable实例

@Override
public <T> Disposable getObservable(Observable<HttpResponse<T>> observable, String tag) {
    return DisposableUtils.getDisposable(observable,tag,onRequestListener);
}

(3)presenter实例中注册rxjava

addSubscription(mModel.getObservable(HttpApiService.getInstance().getRemoteData(url,paramsMap),tag));

定义Disposable通用类方便每次调用,没有用onNext,onError,onComplete等方法实现。

不足之处,欢迎斧正,不胜感激!!!

上一篇下一篇

猜你喜欢

热点阅读