Kotlin的JobCancellationException操作


在使用协程(Deferred)请求网络的时候,往往会加取消请求的操作,在这里就用到了协程的取消cancel()

JobCancellationException

但是,但是在使用cancel()取消的时候,会报JobCancellationException异常,是正常取消协程的异常,所以我们需要这样做:

1
2
3
4
5
6
7
8
9
10
11
12

fun Deferred<Any>?.cancelByActive() = this?.run {
try {
if (isActive) {
cancel()
}
} catch (_: JobCancellationException) {

} catch (e: Exception) {
e.printStackTrace()
}
}

不能单独写一个catch (e: Exception),需要另外catch异常JobCancellationException