测试已测试 | ✗ |
语言语言 | SwiftSwift |
许可证 | MIT |
发布最后发布 | 2017年4月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 JPAlary 维护。
依赖项 | |
RxSwift | ~> 3.3 |
RxCocoa | ~> 3.3 |
Swift 中 Interceptor
的这种实现与 SwiftInterceptor 的一样。它只是使用了 RxSwift 而不是闭包来进行异步部分。
这种 "拦截器" 概念来自 Android 库 Okhttp 中的拦截器实现(参见 Okhttp 拦截器维基)。当您想在提供处理对象之前和之后修改/执行某些操作时,这种机制非常强大。将拦截器看作是输入对象源和目标最终位置之间的中间件。
在这个 Swift 实现中,还添加了两个额外的元素:
Input
对象的可观察序列。有了拦截器,您就有了一个
最后,由于它具有泛型,因此您可以在其他上下文中使用这种机制。发挥您的创造力! :)
首先要做的是创建您需要的拦截器。记住,拦截器是为了拦截输入对象和/或输出对象而设计的。请记得按照关心的事项分组您的拦截器,并避免重复。
为此,您只需遵守 Interceptor 协议即可。
protocol Interceptor {
associatedtype Input
func intercept(chain: InterceptorChain<Input>) -> Observable<Input>
}
拦截输入
struct MyInterceptor: Interceptor {
func intercept(chain: InterceptorChain<URLRequest>) -> Observable<URLRequest> {
// 1) Retrieve the input object (the request) and unwarpped the value
guard let request = chain.input else {
return chain.proceed()
}
// 2) Do things with/on the request
// 3) Continue the chaining with a new value
return chain.proceed(object: request)
}
}
当您实现了您的拦截器后,就结束了!
要启动过程
let disposeBag = DisposeBag()
// 1) I create an instance of interceptor chain. You can add many interceptor you want.
let chain = InterceptorChain(input: request)
.add(interceptor: AnyInterceptor(base: MyInterceptor()))
// 2) Launch the process
chain
.proceed()
.subscribe { (event) in
// 3) You get your data in the `.next` case
}
.disposed(by: disposeBag)
}
关于拦截器机制的更多解释,请参阅okhttp 维基中的文档。对于非 RxSwift 粉丝,您可以查看不依赖任何库的 SwiftInterceptor 实现。