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.下载地址
点击去下载
阅读全文
0 0
- Rxjava2 Retrofit2 和 mvp再封装
- 整合MVP+Retrofit2+RxJava2
- Mvp+Retrofit2+RxJava2 项目中使用的简洁封装
- Mvp+Retrofit2+RxJava2 项目中使用的简洁封装
- Android使用Retrofit2+RxJava2+MVP封装实现购物车
- Rxjava2和Retrofit2网络库的封装
- retrofit2+rxjava2封装解析
- 简单封装retrofit2+rxjava2
- Rxjava2+okhttp3+Retrofit2封装
- Rxjava2+MVP+Retrofit2关系图
- mvp+rxjava2+retrofit2项目框架
- Mvp+rxjava2+Retrofit2 结构框架
- RxJava2+Retrofit2实现网络请求和解析封装
- RxJava2 + Retrofit2 优雅简洁封装
- Retrofit2+Rxjava2联网的封装
- RxJava2+Retrofit2+MVP+lamdba仿微信朋友圈Demo
- RxJava2 + Retrofit2 + Mvp + Dagger2框架搭建
- Retroit+rxjava2.0+mvp封装
- 【CodeForces 429D】Tricky Function 【思维转化+分治求最近点对】
- 编写“木马生成器”软件总结
- 【数据结构】栈与队列基础
- Spring事务管理@Transactional
- 主机序和网络序
- Rxjava2 Retrofit2 和 mvp再封装
- 第一个数据库联动web应用
- linux初学之sshd远程登陆
- SAP FIORI教程——如何设置Launchpad的多语言文件(SAP Cloud 版)
- 处理数字--cookbook读书笔记
- python图像处理库Pillow入门(一)
- 单点登录(SSO)
- Vmware虚拟机三种网络模式详解
- 单例模式