美文网首页
Android - Retrofit + Rx + OkHttp

Android - Retrofit + Rx + OkHttp

作者: 是刘航啊 | 来源:发表于2019-04-03 11:07 被阅读0次

    感谢玩Android提供的API

    Retrofit + Rx + OkHttp MVP

    MVP 模式下的 Retrofit + Rx + OkHttp 网络上有许多,这篇文章是自己对 MVP 的一些理解和感悟,希望能够帮助到读者。

    准备工作

    • 依赖
    • 网络
    • 基类
    • MVP 使用

    依赖

    
        //Okhttp
        implementation 'com.squareup.okhttp3:logging-interceptor:3.+'
    
        //rxjava
        implementation 'io.reactivex.rxjava2:rxjava:2.+'
        implementation 'io.reactivex.rxjava2:rxandroid:2.+'
    
        //retrofit
        implementation 'com.squareup.retrofit2:retrofit:2.+'
        implementation 'com.google.code.gson:gson:2.+'
    
        //Gson 库
        implementation 'com.squareup.retrofit2:converter-gson:2.+'
    
        //转换器,请求结果转换成Model
        implementation 'com.squareup.retrofit2:adapter-rxjava2:2.+'
    
    

    网络封装 RetrofitManager

         public class RetrofitManager {
    
             private static final int DEFAULT_TIME_OUT = 30;//超时时间
             private static final int DEFAULT_READ_TIME_OUT = 60;//读写超时
             long SIZE_OF_CACHE = 10 * 1024 * 1024; // 10 MB
             String cacheFile = App.getApplication().getCacheDir() + "/mvp/http";
             Cache cache = new Cache(new File(cacheFile), SIZE_OF_CACHE);
             static volatile RetrofitManager retrofitManager = null;
             private Retrofit mRetrofit;
            
             private RetrofitManager() {
                 //初始化okhttp
                 OkHttpClient.Builder builder = new OkHttpClient.Builder();
                 // log用拦截器
                 HttpLoggingInterceptor loggingInterceptor = new           HttpLoggingInterceptor();
                 // 开发模式记录整个body,否则只记录基本信息如返回200,http协议版本等
                 if (BuildConfig.DEBUG) {
                     loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                 } else {
                     loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
                 }
    
              builder.addInterceptor(new Interceptor() {
                  @Override
                  public Response intercept(Chain chain) throws IOException {
                      Request request = chain.request().newBuilder().build();
                      return chain.proceed(request);
                  }
              });
    
              builder.cache(cache)        //设置缓存目录
                     .addInterceptor(loggingInterceptor)
                     .connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)//设置超时
                     .readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)
                     .writeTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)
                     .retryOnConnectionFailure(true);//错误重连
    
              OkHttpClient client = builder.build();
    
              mRetrofit = new Retrofit.Builder()
                          .baseUrl(API.BASE_URL)
                         //设置 Json 转换器
                          .addConverterFactory(GsonConverterFactory.create())
                         //添加call转换器将call转换成Observe(观察者)
                          .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                          .client(client)
                          .build();
              }
    
              /**
               * DCL双重检索
               * 单例模式
               * @return
               */
               public static RetrofitManager getRetofitManager(){
                   if(retrofitManager==null){
                       synchronized (RetrofitManager.class) {
                           if (retrofitManager == null) {
                               retrofitManager = new RetrofitManager();
                           }
                       }
                   }
                return  retrofitManager;
               }
    
              /**
               * 获取对应的Service
               *
               * @param service Service 的 class
               * @param <T>
               * @return
               */
               public <T> T create(Class<T> service) {
                    return mRetrofit.create(service);
               }
    
          }
    
    

    基类

    BasePresenter

    
        public interface BasePresenter<T> {
    
            /**
             * 绑定
             */
            void attachView(T t);
    
            /**
             * 解除绑定
             */
            void detachView();
    
        }
    
    

    BaseLoader

    
        public class BaseLoader<T> implements Function<Response<T>, T> {
    
            @Override
            public T apply(Response<T> tResponse) throws Exception {
                //todo 可以自定义处理回掉参数
                return tResponse.getData();
            }
        }
    
    

    ObjectLoader

    protected <T> Observable<T> observe(Observable<T> observable) {  
       //被观察者线程  io线程,读写,网络操作
       return observable.subscribeOn(Schedulers.io())
        .unsubscribeOn(Schedulers.io())
      //观察者线程  Androidui线程
        .observeOn(AndroidSchedulers.mainThread());
     }
    
    

    BaseView

    
        public interface BaseView {
            //todo 例如获取token等
        }
    
    

    MVP 使用 ( 面向接口 )

    • 请求地址
        public interface API {
            String BASE_URL = "https://www.wanandroid.com/";
            String TEST = "friend/json";
        }
    
    • 将页面要用到的接口统一抽取

    MainContract

    
        public class MainContract {
    
            /**
             * P 层
             */
            public interface Presenter extends BasePresenter<View> {
                void showMessage();
            }
    
            /**
             * V 层
             */
            public interface View extends BaseView {
                void showSuccess(String s);
                void showFail(String s);
            }
    
            /**
             * M 层
             */
            public interface Service {
                @GET(API.TEST)
                Observable<Response<List<TestEntity>>> getMessage();
            }
    
        }
    
    
    • M

    TestEntity

    
        public class TestEntity implements Serializable {
    
            private String icon;
            private String id;
            private String link;
            private String name;
            private String order;
            private String visible;
    
            public String getIcon() {
                return icon;
            }
    
            public void setIcon(String icon) {
                this.icon = icon;
            }
    
            public String getId() {
                return id;
            }
    
            public void setId(String id) {
                this.id = id;
            }
    
            public String getLink() {
                return link;
            }
    
            public void setLink(String link) {
                this.link = link;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public String getOrder() {
                return order;
            }
    
            public void setOrder(String order) {
                this.order = order;
            }
    
            public String getVisible() {
                return visible;
            }
    
            public void setVisible(String visible) {
                this.visible = visible;
            }
    
        }
    
    
    • P

    MainLoader

    
    public class MainLoader extends ObjectLoader {
    
        private MainContract.Service mainService;
    
        public MainLoader(){
          mainService = RetrofitManager.getRetofitManager().create(MainContract.Service.class);
        }
    
        public Observable<List<TestEntity>> getMessage(){
            return observe(mainService.getMessage()).map(new BaseLoader<List<TestEntity>>());
        }
    
    }
    
    

    MainPresenterImpl

        public class MainPresenterImpl implements MainContract.Presenter {
    
        private MainContract.View view;
        private MainLoader mainLoader;
        private Context context;
    
        public MainPresenterImpl(Context context) {
            this.context = context;
            this.mainLoader = new MainLoader();
        }
    
        @Override
        public void attachView(MainContract.View view) {
            this.view = view;
        }
    
        @Override
        public void detachView() {
            this.view = null;
        }
    
        @Override
        public void showMessage() {
    
                Observable<List<TestEntity>> observable = null;
                try {
                    observable = mainLoader.getMessage();
                } catch (Exception e) {
                    view.showFail(context.getResources().getString(R.string.request_fail));
                    return;
                }
    
                observable.subscribe(new Consumer<List<TestEntity>>() {
                    @Override
                    public void accept(List<TestEntity> o) {
                        //这里没有处理,只是返回测试结果,具体实现看功能
                        view.showSuccess(new Gson().toJson(o));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    //异常封装
                        view.showFail(throwable.getMessage());
                    }
                });
            }
    
        }
    
    • V

    MainActivity

    
    public class MainActivity extends AppCompatActivity implements MainContract.View {
    
            private MainPresenterImpl mainPresenter;
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                ButterKnife.bind(this);
    
                mainPresenter = new MainPresenterImpl(this);
                mainPresenter.attachView(this);
                mainPresenter.showMessage();
    
            }
    
    
            @Override
            protected void onDestroy() {
                super.onDestroy();
                mainPresenter.detachView();
            }
    
            @Override
            public void showSuccess(String s) {
                ToastUtil.getToastUtil(this).showToast("success>>>>>"+s);
            }
    
            @Override
            public void showFail(String s) {
                ToastUtil.getToastUtil(this).showToast("fail>>>>>"+s);
            }
    
        }
    
    

    感谢玩Android提供的API

    这是第一次写博客,肯定避免不了写错的地方,如果有写错的地方,可以通过留言评论。如果您觉得这篇文章对您有帮助,希望您帮忙点个赞,感谢!

    相关文章

      网友评论

          本文标题:Android - Retrofit + Rx + OkHttp

          本文链接:https://www.haomeiwen.com/subject/gplabqtx.html