博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
RxRetrofit-终极封装-深入浅出&入门
阅读量:6964 次
发布时间:2019-06-27

本文共 2751 字,大约阅读时间需要 9 分钟。

背景

今年Android移动各大门户网站最热门的无非RxJava-Retrofit-OkHttp,所以准备强势入手一波封装,解决代码复用性的问题,这篇先先来个简单的压压惊,看看RxJava-Retrofit结合的使用基础要点,后续会出一些列的专栏优化一套完善的请求封装。

效果

这里写图片描述

懒人简单的使用方式

为什么称为懒人,因为你什么都不用做,直接按照一般案例写rx和retrofit的使用

  • 引入需要的包
/*rx-android-java*/    compile 'com.squareup.retrofit:adapter-rxjava:+'    compile 'com.trello:rxlifecycle:+'    compile 'com.trello:rxlifecycle-components:+'    /*rotrofit*/    compile 'com.squareup.retrofit2:retrofit:+'    compile 'com.squareup.retrofit2:converter-gson:+'    compile 'com.squareup.retrofit2:adapter-rxjava:+'    compile 'com.google.code.gson:gson:+'复制代码
  • 创建一个service定义请求的接口

    /*** service统一接口数据* Created by WZG on 2016/7/16.*/public interface HttpService {  @POST("AppFiftyToneGraph/videoLink")  Observable
    getAllVedioBy(@Body boolean once_no);}复制代码
  • 创建一个retrofit对象

//手动创建一个OkHttpClient并设置超时时间        okhttp3.OkHttpClient.Builder builder = new OkHttpClient.Builder();        builder.connectTimeout(5, TimeUnit.SECONDS);        Retrofit retrofit = new Retrofit.Builder()                .client(builder.build())                .addConverterFactory(GsonConverterFactory.create())                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())                .baseUrl(HttpManager.BASE_URL)                .build();复制代码
  • http请求处理
//        加载框        final ProgressDialog pd = new ProgressDialog(this);        HttpService apiService = retrofit.create(HttpService.class);        Observable
observable = apiService.getAllVedioBy(true); observable.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe( new Subscriber
() { @Override public void onCompleted() { if (pd != null && pd.isShowing()) { pd.dismiss(); } } @Override public void onError(Throwable e) { if (pd != null && pd.isShowing()) { pd.dismiss(); } } @Override public void onNext(RetrofitEntity retrofitEntity) { tvMsg.setText("无封装:\n" + retrofitEntity.getData().toString()); } @Override public void onStart() { super.onStart(); pd.show(); } } );复制代码

终极封装专栏


源码


建议

转载地址:http://htwsl.baihongyu.com/

你可能感兴趣的文章
CocoaPods的使用
查看>>
find命令详解
查看>>
变频电源内部IGBT模块的作用是什么样的
查看>>
手机PDF文件怎么压缩得更小,PDF文件如何压缩?
查看>>
超声波清洗机对人体有辐射,有伤害吗?
查看>>
区块链成多地政府工作报告新热词
查看>>
论职场沟通的重要性
查看>>
velocity模板中后台返回html,前端无法跳转页面
查看>>
AJPFX:如何保证对象唯一性呢?
查看>>
天禹智控--现场标准气体如何使用?
查看>>
CSS3:border-radius隐藏的威力
查看>>
springMVC 返回类型选择 以及 SpringMVC中model,modelMap
查看>>
存储型XSS进阶 [猜测规则,利用Flash addCallback构造XSS]
查看>>
[Openshift Origin 3]OpenShift 3 : 基于Docker的私有PaaS平台
查看>>
php的执行时间啊
查看>>
jetty/eclipse:A full JDK (not just JRE) is require
查看>>
linux awk命令详解
查看>>
angular中将$sce服务封装成过滤器
查看>>
html 可拖动宽度的div方法
查看>>
openvz 双网卡桥接
查看>>