Rxjava2 Retrofit2 和 mvp再封装

来源:互联网 发布:php 设置头部 编辑:程序博客网 时间:2024/06/07 17:47

这个框架还是挺好用的,不过我技术比较渣,只能封装成这样了,望大牛指点。

1.添加类库

    compile 'com.squareup.retrofit2:retrofit:2.3.0'    compile 'com.squareup.retrofit2:converter-gson:2.3.0'    compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'    compile 'io.reactivex.rxjava2:rxjava:2.0.1'    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'    compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'

2. RetrofitHelper类简单封装

    package com.zlc.rxmvp.http;    import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;    import com.ssdk.dongkang.App;    import com.ssdk.dongkang.utils.LogUtil;    import java.io.File;    import java.io.IOException;    import java.util.concurrent.TimeUnit;    import okhttp3.Cache;    import okhttp3.Interceptor;    import okhttp3.OkHttpClient;    import okhttp3.Request;    import okhttp3.Response;    import okhttp3.logging.HttpLoggingInterceptor;    import retrofit2.Retrofit;    import retrofit2.converter.gson.GsonConverterFactory;    /**     * Created by zlc     * Retrofit帮助类     */    public class RetrofitHelper {        //设置缓存目录        private static File cacheFile;        private static long maxSize = 8 * 1024 * 1024; //缓存文件大小        private final  static  long TIMEOUT = 500;  //超时时间        private Cache mCache;        private final static String baseUrl = HttpUrl.DOMAIN;        private OkHttpClient mClient;        private Retrofit mRetrofit;        private final HttpService mHttpService;        private static String TAG;        private RetrofitHelper(){            cacheFile = new File(App.getContext().getCacheDir().getAbsolutePath(), "dk_cache");            if(!cacheFile.exists()){                cacheFile.mkdir();            }            TAG = this.getClass().getSimpleName();            mHttpService = getRetrofit().create(HttpService.class);        }        //单例 保证对象唯一        public static RetrofitHelper getInstance(){            return SingletonHolder.retrofitHelper;        }        private static class SingletonHolder{            private final static RetrofitHelper retrofitHelper =  new RetrofitHelper();        }        //创建缓存文件和目录        private Cache getCache(){            if(mCache ==null)                mCache = new Cache(cacheFile, maxSize);            return mCache;        }        //获取OkHttpClient        private OkHttpClient getOkHttpClient(){            if(mClient ==null) {                mClient = new OkHttpClient.Builder()                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)                        //.addInterceptor(headInterceptor)                        .addInterceptor(loggingInterceptor)                        .cache(getCache())      //设置缓存                        .build();            }            return mClient;        }        //获取Retrofit对象        public Retrofit getRetrofit(){            if(mRetrofit==null) {                mRetrofit = new Retrofit.Builder()                        .baseUrl(baseUrl)                        .addConverterFactory(GsonConverterFactory.create())        //添加Gson支持                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())  //添加RxJava支持                        .client(getOkHttpClient())                                 //关联okhttp                        .build();            }            return mRetrofit;        }        //获取服务对象        public static synchronized HttpService getService(){            return RetrofitHelper.getInstance().mHttpService;        }        //日志拦截器        private final static Interceptor headInterceptor = new Interceptor() {            @Override            public Response intercept(Chain chain) throws IOException {                Request mRequest=chain.request();                //在这里你可以做一些想做的事,比如token失效时,重新获取token                //或者添加header等等                return chain.proceed(mRequest);            }        };        //日志拦截器        private final static HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {            @Override            public void log(String message) {                LogUtil.e(TAG + " : log",message);            }        }).setLevel(HttpLoggingInterceptor.Level.BODY);    }

3. HttpService类简写

public interface HttpService{        @FormUrlEncoded        @POST("checkhardWare.htm")        Observable<BaseInfo<LastTimeInfo>> checkHardWare(@FieldMap Map<String,String> map);   }

4. HttpUtils类简单封装

    package com.zlc.rxmvp.http;    import android.text.TextUtils;    import android.util.Log;    import android.widget.Toast;    import com.ssdk.dongkang.App;    import com.ssdk.dongkang.utils.LogUtil;    import io.reactivex.Observable;    import io.reactivex.Observer;    import io.reactivex.android.schedulers.AndroidSchedulers;    import io.reactivex.disposables.Disposable;    import io.reactivex.schedulers.Schedulers;    /**     * Created by zlc      * 网络请求工具类     */    public class HttpUtil {        //Post方式请求网络        public static void post(Observable observable, final OnResultListener resultListener){            setSubscriber(observable, new Observer() {                Disposable d;                @Override                public void onSubscribe(Disposable d) {                    LogUtil.e("onSubscribe",d+"");                    this.d = d;                }                @Override                public void onNext(Object value) {                    LogUtil.e("onNext",value+"");                    if(value == null){                        LogUtil.e("onNext ","JSON解析失败");                    }else if(resultListener!=null){                        resultListener.onSuccess(value);                    }                }                @Override                public void onError(Throwable error) {                    errorDispose(error, resultListener);                    if(d != null)                        d.dispose();                }                @Override                public void onComplete() {                    LogUtil.e("onComplete","请求完成");                    if(d != null)                        d.dispose();                }            });        }        //Get方式请求网络        public static void get(Observable observable, final OnResultListener resultListener){            post(observable,resultListener);        }        //订阅事件        public static<T> void setSubscriber(Observable<T> observable, Observer<T> observer){            observable.subscribeOn(Schedulers.newThread())  //开启新线程                    .observeOn(AndroidSchedulers.mainThread()) //ui操作放主线程                    .subscribe(observer);        }        //接口回调        public interface OnResultListener<T>{            void onSuccess(T t);            void onError(Throwable error, String msg);        }        //错误处理        private static void errorDispose(Throwable error, OnResultListener resultListener) {            if(error!=null && resultListener!=null){                resultListener.onError(error,error.getMessage());            }else if(resultListener!=null){                resultListener.onError(new Exception("网络不给力"),"");                Toast.makeText(App.getContext(),"网络不给力",Toast.LENGTH_LONG).show();                return;            }            String e  = error.getMessage();            int code  =0;            if(!TextUtils.isEmpty(e)){                try {                    e = e.substring(e.length()-3,e.length());                    code = Integer.valueOf(e);                }catch (Exception e1){                    Toast.makeText(App.getContext(),"网络不给力",Toast.LENGTH_LONG).show();                }            }            Log.e("错误code",code+"");            if(code>=300&&code<500){                Toast.makeText(App.getContext(),"您的请求迷路了,请稍后再试",Toast.LENGTH_LONG).show();            }else if(code>=500){                Toast.makeText(App.getContext(),"服务器异常,请稍后再试",Toast.LENGTH_LONG).show();            }else{                Toast.makeText(App.getContext(),"网络不给力",Toast.LENGTH_LONG).show();            }        }    }

5. mvp presenter封装

    package com.zlc.rxmvp.mvp;    /**     * Created by zlc on      */    public interface BaseIPresenter{        //销毁View        void onDestoryView();    }    package com.ssdk.dongkang.mvp;    import android.content.Context;    import com.ssdk.dongkang.http.HttpService;    import com.ssdk.dongkang.http.RetrofitHelper;    /**     * Created by zlc on      * 所有Presenter层的父类     */    public  abstract class BasePresenter <T extends BaseIView> implements BaseIPresenter{        protected  T mView;        protected Context mContext;        protected final HttpService mHttpService;        public BasePresenter(T view,Context context){            this.mView = view;            this.mContext = context;            mHttpService = RetrofitHelper.getService();        }        //请求网络 加载数据方法        protected  abstract void initData();        //获取HttpService对象        public HttpService getService() {            return mHttpService;        }        @Override        public void onDestoryView() {            if(mView !=null)                mView = null;        }    }

6. mvp view封装

    package com.zlc.rxmvp.mvp;    /**     * Created by zlc on      * 所有View层的父类 只是为了一个通用     */    public interface BaseIView {        //数据请求失败 View层处理        void onError();    }

7.联系方式

qq:1509815887@qq.com email : zlc921022@163.com phone : 18684732678

8.下载地址
点击去下载

原创粉丝点击