Retrofit目前较为流行的网络请求框架,与之前的对比如下:

retrofit负责封装请求接口,okhttp负责完成网络请求:

简单使用步骤:Android Retrofit 2.0 的详细 使用攻略(含实例讲解) - 简书
步骤1:添加Retrofit库的依赖
步骤2:创建 接收服务器返回数据 的类
步骤3:创建 用于描述网络请求 的接口
步骤4:创建 Retrofit 实例
步骤5:创建 网络请求接口实例 并 配置网络请求参数
步骤6:发送网络请求(异步 / 同步)
支持http所有请求方法:put,get,post,delete,path,head,options。
例如:


baseUrl为基地址,完整的url为:http://fanyi.youdao,com/users/user/repos,user会被替换为输入的字符串。
标记类:



请求参数:

举例:


数据解析器:

目前更新到了rxjava2.x 四个基础的接口:这可能是最好的RxJava 2.x 教程(完结版) - 简书
Publisher、Subscriber、Subscription、Processor。Publisher 可以发出一系列的事件,而 Subscriber 负责和处理这些事件。
其中用的比较多的自然是 Publisher 的 Flowable,它支持背压。
背压概念:背压是指在异步场景中,被观察者发送事件速度远快于观察者的处理速度的情况下,一种告诉上游的被观察者降低发送速度的策略。
设计采用观察者模式:
Observable ( 被观察者 ) / Observer ( 观察者 )
Flowable (被观察者)/ Subscriber (观察者)
线程调度:subscribeOn() 指定的就是发射事件的线程,observerOn 指定的就是订阅者接收事件的线程。
例子:被观察者在io线程,观察者在主线程。

四种线程可以选择:
Schedulers.io()代表io操作的线程, 通常用于网络,读写文件等io密集型的操作;
Schedulers.computation()代表CPU计算密集型的操作, 例如需要大量计算的操作;
Schedulers.newThread()代表一个常规的新线程;
AndroidSchedulers.mainThread()代表Android的主线程
操作符的操作参考上面的链接
网友评论