前言

上篇我们介绍了 APT 在 Router 框架中的使用,通过注解处理器搜集路由信息,本篇我们来聊一下 Router 的运行机制。

为什么要用拦截器?

我们先看一下路由的使用场景

服务端下发一个链接,首先我们需要判断这个链接是否在路由表中,如果是则取出对应的页面信息,否则需要判断该链接是否支持支持内置浏览器打开,经过层层过滤,最终得到目标页面。这其中可能还要插入一些通用参数,有没有感觉和 OkHttp 的一次网络请求很相似?

使用拦截器,可以自由的插入一些自定义逻辑,使我们的路由更加灵活。

拦截器原理

先来看一张调用图

android父布局拦截点击事件 android拦截器_ide


有没有觉得拦截器和 Android 触摸机制很相似,区别是拦截器可以直接终止链式调用,返回结果,而触摸事件则必须经过层层传递,最终返回。

实现拦截器层层调用主要是通过 Chain 这个链式调用

interface Interceptor {
fun intercept(chain: Chain): Response
interface Chain {
fun request(): Request
fun proceed(request: Request): Response
fun call(): Call
}
}

复制代码注:此处省略了部分方法

拦截器需要实现 intercept 方法,提供一个 chain 参数

Chain 中的 request 方法可以获得请求实体,根据请求信息可以直接返回 Response,也可以通过 proceed 方法把请求交给下一个拦截器处理。

下面来看一下 Chain 的实现

class RealInterceptorChain(
private val interceptors: List,
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
}
}

复制代码注:此处省略了部分代码

构造函数:

interceptors 所有连接器集合

index 拦截器执行序号

request 请求实体

call 请求执行者

逻辑主要在 proceed 这个方法里

首先判断 index 是否溢出,溢出直接报错

然后将 index + 1,构造下一个调用链,执行拦截请求。这里就可以做到链式循环调用

最后是做结果校验,返回最终结果

简单地几行代码就实现了链式调用,就是这么简单。