前言
上篇我們介紹了 APT 在 Router 框架中的使用,通過(guò)注解處理器搜集路由信息迹蛤,本篇我們來(lái)聊一下 Router 的運(yùn)行機(jī)制透乾。
為什么要用攔截器?
我們先看一下路由的使用場(chǎng)景
服務(wù)端下發(fā)一個(gè)鏈接,首先我們需要判斷這個(gè)鏈接是否在路由表中,如果是則取出對(duì)應(yīng)的頁(yè)面信息,否則需要判斷該鏈接是否支持支持內(nèi)置瀏覽器打開芙贫,經(jīng)過(guò)層層過(guò)濾,最終得到目標(biāo)頁(yè)面傍药。這其中可能還要插入一些通用參數(shù)磺平,有沒有感覺和 OkHttp 的一次網(wǎng)絡(luò)請(qǐng)求很相似魂仍?
使用攔截器,可以自由的插入一些自定義邏輯拣挪,使我們的路由更加靈活蓄诽。
攔截器原理
先來(lái)看一張調(diào)用圖
有沒有覺得攔截器和 Android 觸摸機(jī)制很相似,區(qū)別是攔截器可以直接終止鏈?zhǔn)秸{(diào)用媒吗,返回結(jié)果仑氛,而觸摸事件則必須經(jīng)過(guò)層層傳遞,最終返回闸英。
實(shí)現(xiàn)攔截器層層調(diào)用主要是通過(guò) Chain 這個(gè)鏈?zhǔn)秸{(diào)用
interface Interceptor {
fun intercept(chain: Chain): Response
interface Chain {
fun request(): Request
fun proceed(request: Request): Response
fun call(): Call
}
}
注:此處省略了部分方法
攔截器需要實(shí)現(xiàn) intercept 方法锯岖,提供一個(gè) chain 參數(shù)
Chain 中的 request 方法可以獲得請(qǐng)求實(shí)體,根據(jù)請(qǐng)求信息可以直接返回 Response甫何,也可以通過(guò) proceed 方法把請(qǐng)求交給下一個(gè)攔截器處理出吹。
下面來(lái)看一下 Chain 的實(shí)現(xiàn)
class RealInterceptorChain(
private val interceptors: List<Interceptor>,
private val index: Int,
private val request: Request,
private val call: Call
) : Interceptor.Chain {
private var calls: Int = 0
override fun call(): Call {
return call
}
override fun request(): Request {
return request
}
override fun proceed(request: Request): Response {
if (index >= interceptors.size) throw AssertionError()
calls++
// Call the next interceptor in the chain.
val next = RealInterceptorChain(interceptors, index + 1, request, call)
val interceptor = interceptors[index]
val response = interceptor.intercept(next)
// Confirm that the next interceptor made its required call to chain.proceed().
if (response == null && index + 1 < interceptors.size && next.calls != 1) {
throw IllegalStateException("router interceptor " + interceptor
+ " must call proceed() exactly once")
}
// Confirm that the intercepted response isn't null.
if (response == null) {
throw NullPointerException("interceptor $interceptor returned null")
}
return response
}
}
注:此處省略了部分代碼
構(gòu)造函數(shù):
- interceptors 所有連接器集合
- index 攔截器執(zhí)行序號(hào)
- request 請(qǐng)求實(shí)體
- call 請(qǐng)求執(zhí)行者
邏輯主要在 proceed 這個(gè)方法里
- 首先判斷 index 是否溢出,溢出直接報(bào)錯(cuò)
- 然后將 index + 1辙喂,構(gòu)造下一個(gè)調(diào)用鏈捶牢,執(zhí)行攔截請(qǐng)求。這里就可以做到鏈?zhǔn)窖h(huán)調(diào)用
- 最后是做結(jié)果校驗(yàn)巍耗,返回最終結(jié)果
簡(jiǎn)單地幾行代碼就實(shí)現(xiàn)了鏈?zhǔn)秸{(diào)用秋麸,就是這么簡(jiǎn)單。
源碼
總結(jié)
本文主要介紹攔截器的實(shí)現(xiàn)原理炬太,希望對(duì)大家有幫助灸蟆。