// name 参数在这会生成 setDomainToGoogleIfAbsent方法,可随意指定名称
// className 参数在这会生成RxGoogleHttp类,可随意指定名称
@Domain(name = “Google”, className = “Google”)
public static String GOOGLE = “https://www.google.com”;
}
以上配置www.wanandroid.com
为默认域名,www.google.com
为非默认域名
多BaseUrl处理
//使用默认域名发请求
RxHttp.get("/service/…")
.toSrt().await()
//使用google域名方式一:传入的url直接带上google域名
RxHttp.get(“https://wwww.google.com/service/…”)
.toSrt().await()
//使用google域名方式二:调用setDomainToGoogleIfAbsent方法
RxHttp.get("/service/…")
.setDomainToGoogleIfAbsent()
.toSrt().await()
//使用google域名方式三:直接使用RxGoogleHttp类发送请求
RxGoogleHttp.get("/service/…")
.toSrt().await()
注意:手动传入的域名优先级别最高,其次是调用setDomainToXxx方法,最后才会使用默认域名
动态域名处理
//直接对url重新赋值即可,改完立即生效
Url.BASE_URL = “https://www.baidu.com”;
RxHttp.get("/service/…")
.toSrt().await()
//此时请求的url为 https://www.baidu.com/service/…
我想大部分人的接口返回格式都是这样的
class Response {
var code = 0
var msg : String? = null
var data : T
}
拿到该对象的第一步就是对code做判断,如果code != 200
(假设200代表数据正确),就会拿到msg字段给用户一些错误提示,如果等于200,就拿到data字段去更新UI,常规的写法是这样的
val response = RxHttp.get("/service/…")
.toClass
.await()
if (response.code == 200) {
//拿到data字段(Student)刷新UI
} else {
//拿到msg字段给出错误提示
}
试想一下,一个项目少说也有十几个这样的接口,如果每个接口读取这么判断,就显得不够优雅,也可以说是灾难,相信也没有人会这么干。而且对于UI来说,只需要data字段即可,错误提示啥的我管不着。
那有没有什么办法,能直接拿到data字段,并且对code做出统一判断呢?有的,直接上代码
val student = RxHttp.get("/service/…")
.toResponse() //调用此方法,直接拿到data字段,也就是Student对象
.await()
//直接开始更新UI
可以看到,这里调用了toResponse()
方法,就直接拿到了data字段,也就是Student对象。
此时,相信很多人会有疑问,
业务code哪里判断的?
业务code非200时,msg字段怎么拿到?
为此,先来回答第一个问题,业务code哪里判断的?
其实toResponse()
方法并不是RxHttp内部提供的,而是用户通过自定义解析器,并用@Parser
注解标注,最后由注解处理器rxhttp-compiler
自动生成的,听不懂?没关系,直接看代码
@Parser(name = “Response”)
open class ResponseParser : AbstractParser {
//以下两个构造方法是必须的
protected constructor() : super()
constructor(type: Type) : super(type)
@Throws(IOException::class)
override fun onParse(response: okhttp3.Response): T {
val type: Type = ParameterizedTypeImpl[Response::class.java, mType] //获取泛型类型
val data: Response = convert(response, type) //获取Response对象
val t = data.data //获取data字段
if (data.code != 200 || t == null) { //code不等于200,说明数据不正确,抛出异常
throw ParseException(data.code.toString(), data.msg, response)
}
return t
}
}
上面代码只需要关注两点即可,
第一点,我们在类开头使用了@Parser
注解,并为解析器取名为Response
,所以就有了toResponse()
方法(命名方式为:to + Parser注解里设置的名字);
第二点,我们在if
语句里,对code做了判断,非200或者data为空时,就抛出异常,并带上了code及msg字段,所以我们在异常回调的地方就能拿到这两个字段
接着回答第二个问题,code非200时,如何拿到msg字段?直接上代码,看一个使用协程发送请求的完整案例
//当前环境在Fragment中
fun getStudent() {
//rxLifeScope在rxLife-coroutine库中,需要单独依赖
rxLifeScope.launch({ //通过launch方法开启一个协程
val student = RxHttp.get("/service/…")
.toResponse()
.await()
}, {
//异常回调,这里的it为Throwable类型
val code = it.code
val msg = it.msg
})
}
注:RxLifeScope 是 RxLife-Coroutine库中的类,本文后续会详细介绍
上面的代码,在异常回调中便可拿到code及msg字段,需要注意的是,it.code
及it.msg
是我为Throwable类扩展的两个属性,代码如下:
val Throwable.code: Int
get() {
val errorCode = when (this) {
is HttpStatusCodeException -> this.statusCode //Http状态码异常
is ParseException -> this.errorCode //业务code异常
else -> “-1”
}
return try {
errorCode.toInt()
} catch (e: Exception) {
-1
}
}
val Throwable.msg: String
get() {
return if (this is UnknownHostException) { //网络异常
“当前无网络,请检查你的网络设置”
} else if (
this is SocketTimeoutException //okhttp全局设置超时
|| this is TimeoutException //rxjava中的timeout方法超时
|| this is TimeoutCancellationException //协程超时
) {
“连接超时,请稍后再试”
} else if (this is ConnectException) {
“网络不给力,请稍候重试!”
} else if (this is HttpStatusCodeException) { //请求失败异常
“Http状态码异常”
} else if (this is JsonSyntaxException) { //请求成功,但Json语法异常,导致解析失败
“数据解析失败,请检查数据是否正确”
} else if (this is ParseException) { // ParseException异常表明请求成功,但是数据不正确
this.message ?: errorCode //msg为空,显示code
} else {
“请求失败,请稍后再试”
}
}
到这,业务code统一判断就介绍完毕,上面的代码,大部分人都可以简单修改后,直接用到自己的项目上,如ResponseParser
解析器,只需要改下if
语句的判断条件即可
map
操作符很好理解,RxJava及协程的Flow都有该操作符,功能都是一样,用于转换对象,如下:
val student = RxHttp.postForm("/service/…")
.toStr()
.map { it.length } //String转Int
.tryAwait() //这里返回 Student? 对象,即有可能为空
OkHttp提供了全局的读、写及连接超时,有时我们也需要为某个请求设置不同的超时时长,此时就可以用到RxHttp的timeout(Long)
方法,如下:
val student = RxHttp.postForm("/service/…")
.toResponse()
.timeout(3000) //超时时长为3s
.await()
OkHttp为我们提供了全局的失败重试机制,然而,这远远不能满足我们的需求,比如,我就部分接口需要失败重试,而不是全局的;我需要根据某些条件来判断是否需要重试;亦或者我需要周期性重试,即间隔几秒后重试等等
如我们需要在网络出现异常时,重试2次,每次间隔1秒,代码如下:
val student = RxHttp.postForm("/service/…")
.toResponse()
.retry(2, 1000) { //重试2次,每次间隔1s
it is ConnectException //如果是网络异常就重试
}
.await()
retry()
方法共有3个参数,分别是重试次数、重试周期、重试条件,都有默认值,3个参数可以随意搭配,如下:
/**
如果服务器返回列表数据,则我们可对列表进行过滤操作,如下:
val students = RxHttp.postForm("/service/…")
.toList()
.filter{ it.age > 20 } //过滤年龄大于20岁的学生
.await()
还可以选用filterTo
操作符,将过滤后的数据添加到指定列表中,如下:
val list = mutableListOf()
val students = RxHttp.postForm("/service/…")
.toList()
.filterTo(list){ it.age > 20 } //过滤年龄大于20岁的学生
.await() //此时返回的列表对象就是我们传入的列表对象
该操作符可以对服务器返回的列表,做去重操作,如下:
//根据Student对象的hashCode去重
val students = RxHttp.postForm("/service/…")
.toList()
.distinct()
.await()
//根据Student对象的id去重
val students = RxHttp.postForm("/service/…")
.toList()
.distinctBy { it.id }
.await()
//将去重后的数据添加到指定列表中,并且去重时,会对指定列表数据做判断
val list = mutableListOf()
val students = RxHttp.postForm("/service/…")
.toList()
.distinctTo(list) { it.id }
.await()
排序有sortXxx、sortedXxx
两大类型操作符,区别在于sortXxx
在列表内排序,排序完,返回自身,而sortedXxx
在列表外排序,排序完,返回新的列表,这里只对sortXxx
介绍,如下:
//根据id顺序排序
val students = RxHttp.postForm("/service/…")
.toList()
.sortBy { it.id }
.await()
//根据id、age两个字段顺序排序,id优先,其次age
val students = RxHttp.postForm("/service/…")
.toList()
.sortBy({ it.id }, { it.age })
.await()
//返回两个排序对象,自行实现排序规则
val students = RxHttp.postForm("/service/…")
.toList()
.sortWith { student1, student2 ->
student1.id.compareTo(student2.id)
}
.await()
该操作符跟Flow
里面的flowOn
操作符一样,用于指定上游所在线程,如下:
val students = RxHttp.postForm("/service/…")
.toList()
.sortBy { it.id } //IO线程执行
.flowOn(Dispatchers.IO)
.distinctBy { it.id } //Default线程执行
.flowOn(Dispatchers.Default)
.filter{ it.age > 20 } //IO线程执行
.flowOn(Dispatchers.IO)
.flowOn(Dispatchers.Default)
.await()
如果你喜欢kotlin的flow
流,那么asFlow
就派上用场了,如下:
RxHttp.postForm("/service/…")
.toList()
.asFlow()
.collect {
//这里拿到List对象
}
注意:使用asFlow
操作符后,需要使用collect
替代await
操作符
subList
用于截取某段列表,截取范围越界,则抛出越界异常;take
用于从0开始,取n个数据,不足n个时,返回全部,如下:
val students = RxHttp.postForm("/service/…")
.toList()
.subList(1,10) //截取9个数据
.take(5) //从9个中取前5个
.await()
如果我们由两个请求需要并行时,就可以使用该操作符,如下:
//同时获取两个学生信息
suspend void initData() {
val asyncStudent1 = RxHttp.postForm("/service/…")
.toResponse()
.async(this) //this为CoroutineScope对象,这里会返回Deferred
val asyncStudent2 = RxHttp.postForm("/service/…")
.toResponse()
.async(this) //this为CoroutineScope对象,这里会返回Deferred
//随后调用await方法获取对象
val student1 = asyncStudent1.await()
val student2 = asyncStudent2.await()
}
delay
操作符是请求结束后,延迟一段时间返回;而startDelay
操作符则是延迟一段时间后再发送请求,如下:
val student = RxHttp.postForm("/service/…")
.toResponse()
.delay(1000) //请求回来后,延迟1s返回
.await()
val student = RxHttp.postForm("/service/…")
.toResponse()
.startDelay(1000) //延迟1s后再发送请求
.await()
有些情况,我们不希望请求出现异常时,直接走异常回调,此时我们就可以通过两个操作符,给出默认的值,如下:
//根据异常给出默认值
val student = RxHttp.postForm("/service/…")
.toResponse()
.timeout(100) //超时时长为100毫秒
.onErrorReturn {
//如果时超时异常,就给出默认值,否则,抛出原异常
return@onErrorReturn if (it is TimeoutCancellationException)
Student()
else
throw it
}
.await()
//只要出现异常,就返回默认值
val student = RxHttp.postForm("/service/…")
.toResponse()
.timeout(100) //超时时长为100毫秒
.onErrorReturnItem(Student())
.await()
这个就直接看代码吧
val result: Result = RxHttp
.postForm("/service/…")
.toClass()
.awaitResult()
if (result.isSuccess) {
//请求成功,拿到Student对象
val student = result.getOrThrow()
} else {
//请求出现异常,拿到Throwable对象
val throwable = result.exceptionOrNull()
}
拿到kotlin.Result
对象后,我们需要判断请求成功与否,随后在执行相关逻辑
tryAwait
会在异常出现时,返回null,如下:
val student = RxHttp.postForm("/service/…")
.toResponse()
.timeout(100) //超时时长为100毫秒
.tryAwait() //这里返回 Student? 对象,如果出现异常,那它就是null
RxHttp内置了一系列强大又好用的操作符,然而肯定满足不了所有的业务场景,此时我们就可以考虑自定义操作符
自定义takeLast操作符
如我们有这样一个需求,自定义需要在列表尾部取n条数据,不足n条,返回全部
前面我们介绍了take
操作符,它是从0开始,取n条数据,如果不足n条,则全部返回,来看看源码
fun IAwait
count: Int
): IAwait = newAwait {
await().take(count)
}
代码解读,
1、IAwait
是一个接口,如下:
interface IAwait {
suspend fun await(): T
}
该接口仅有一个await()
方法,返回声明的T
2、newAwait
操作符,只是创建了一个IAwait
接口的实现而已,如下:
inline fun
crossinline block: suspend IAwait.() -> R
): IAwait = object : IAwait {
override suspend fun await(): R {
return [email protected]()
}
}
3、由于我们是为IAwait
对象扩展的take
方法,故在内部,我们调用await()
方法它返回Iterable
对象,最后就执行Iterable
对象的扩展方法take(Int)
获取从0开是的n条数据,take(Int)
是系统提供的方法,源码如下:
public fun Iterable.take(n: Int): List {
require(n >= 0) { “Requested element count $n is less than zero.” }
if (n == 0) return emptyList()
if (this is Collection) {
if (n >= size) return toList()
if (n == 1) return listOf(first())
}
var count = 0
val list = ArrayList(n)
for (item in this) {
list.add(item)
if (++count == n)
break
}
return list.optimizeReadOnlyList()
}
ok,回到前面的话题,如何自定义一个操作,实现在列表尾部取n条数据,不足n条,返回全部
看了上面的take(int)
源码,我们就可以很轻松的写出如下代码:
fun IAwait
count: Int
): IAwait = newAwait {
await().takeLast(count)
}
首先,我们对IAwait
扩展了takeLast(Int)
方法,随后调用newAwait
创建了IAwait
接口的实例对象,接着调用await()
方法返回List
对象,最后调用系统为List
扩展的takeLast(Int)
方法
定义好了,我们就可直接使用,如下:
val students = RxHttp.postForm("/service/…")
.toList()
.takeLast(5) //取列表尾部5条数据,不足时,全部返回
.await()
以上操作符,可随意搭配使用,但调用顺序的不同,产生的效果也不一样,这里先告诉大家,以上操作符仅会对上游代码产生影响。
如timeout及retry
:
val student = RxHttp.postForm("/service/…")
.toResponse()
.timeout(50)
.retry(2, 1000) { it is TimeoutCancellationException }
.await()
以上代码,只要出现超时,就会重试,并且最多重试两次。
但如果timeout
、retry
互换下位置,就不一样了,如下:
val student = RxHttp.postForm("/service/…")
.toResponse()
.retry(2, 1000) { it is TimeoutCancellationException }
.timeout(50)
.await()
此时,如果50毫秒内请求没有完成,就会触发超时异常,并且直接走异常回调,不会重试。为什么会这样?原因很简单,timeout及retry
操作符,仅对上游代码生效。如retry操作符,下游的异常是捕获不到的,这就是为什么timeout在retry下,超时时,重试机制没有触发的原因。
在看timeout
和startDelay
操作符
val student = RxHttp.postForm("/service/…")
.toResponse()
.startDelay(2000)
.timeout(1000)
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
.await()
以上代码,必定会触发超时异常,因为startDelay,延迟了2000毫秒,而超时时长只有1000毫秒,所以必定触发超时。 但互换下位置,又不一样了,如下:
val student = RxHttp.postForm("/service/…")
.toResponse()
.timeout(1000)
.startDelay(2000)
.await()
以上代码正常情况下,都能正确拿到返回值,为什么?原因很简单,上面说过,操作符只会对上游产生影响,下游的startDelay
延迟,它是不管的,也管不到。
RxHttp对文件的优雅操作是与生俱来的,在协程的环境下,依然如此,没有什么比代码更具有说服力,直接上代码
val result = RxHttp.postForm("/service/…")
.addFile(“file”, File(“xxx/1.png”)) //添加单个文件
.addFile(“fileList”, ArrayList()) //添加多个文件
.toResponse()
.await()
只需要通过addFile
系列方法添加File对象即可,就是这么简单粗暴,想监听上传进度?简单,再加一个upload
操作符即可,如下:
val result = RxHttp.postForm("/service/…")
.addFile(“file”, File(“xxx/1.png”))
.addFile(“fileList”, ArrayList())
.upload(this) { //此this为CoroutineScope对象,即当前协程对象
//it为Progress对象
val process = it.progress //已上传进度 0-100
val currentSize = it.currentSize //已上传size,单位:byte
val totalSize = it.totalSize //要上传的总size 单位:byte
}
.toResponse()
.await()
我们来看下upload
方法的完整签名,如下:
/**
接着再来看看下载,直接贴代码
val localPath = “sdcard//android/data/…/1.apk”
val student = RxHttp.get("/service/…")
.toDownload(localPath) //下载需要传入本地文件路径
.await()
下载调用toDownload(String)
方法,传入本地文件路径即可,要监听下载进度?也简单,如下:
val localPath = “sdcard//android/data/…/1.apk”
val student = RxHttp.get("/service/…")
.toDownload(localPath, this) { //此this为CoroutineScope对象
//it为Progress对象
val process = it.progress //已下载进度 0-100
val currentSize = it.currentSize //已下载size,单位:byte
val totalSize = it.totalSize //要下载的总size 单位:byte
}
.await()
看下toDownload
方法完整签名
/**
如果你需要断点下载,也是可以的,一行代码的事,如下:
val localPath = “sdcard//android/data/…/1.apk”
val student = RxHttp.get("/service/…")
.setRangeHeader(1000, 300000) //断点下载,设置下载起始/结束位置
.toDownload(localPath, this) { //此this为CoroutineScope对象
//it为Progress对象
val process = it.progress //已下载进度 0-100
val currentSize = it.currentSize //已下size,单位:byte
val totalSize = it.totalSize //要下的总size 单位:byte
}
.await()
老规则,看下setRangeHeader
完整签名
/**
到这,RxHttp协程的基础Api基本介绍完毕,那么问题了,以上介绍的Api都依赖与协程环境,那我这么开启协程呢?亦或者说,我对协程不是很懂,你只要保证安全的前提下,告诉怎么用就行了,ok,那下面如何安全的开启一个协程,做到自动异常捕获,且页面销毁时,自动关闭协程及请求
此时就要引入本人开源的另一个库RxLife-Coroutine,用于开启/关闭协程,并自动异常捕获,依赖如下:
implementation ‘com.ljx.rxlife:rxlife-coroutine:2.0.0’
本文在介绍业务code统一处理的时候,我们用到rxLifeScope属性开启协程,那这个是什么类型呢?看代码
val ViewModel.rxLifeScope: RxLifeScope
get() {
val scope: RxLifeScope? = this.getTag(JOB_KEY)
if (scope != null) {
return scope
}
return setTagIfAbsent(JOB_KEY, RxLifeScope())
}
val LifecycleOwner.rxLifeScope: RxLifeScope