TestsTested | ✗ |
LangLanguage | SwiftSwift |
License | MIT |
ReleasedLast Release | Apr 2017 |
SwiftSwift Version | 3.0 |
SPMSupports SPM | ✗ |
Maintained by JPAlary.
Depends on: | |
RxSwift | ~> 3.3 |
RxCocoa | ~> 3.3 |
This implementation of Interceptor
in Swift is the same as the SwiftInterceptor one. It just used RxSwift instead of closure for the asynchronous part.
This Interceptor "concept" comes from the Interceptor implementation in the library Okhttp for Android (see Okhttp interceptor wiki). This mechanism is very powerful when you want to modify/do some actions on an input object before and after the process it was given for. See the interceptors as a middleware between the source of your input object and its final destination.
In this Swift implementation, two more things has been added:
Input
object.With Interceptors, you have:
To finish, as it's generic, you can apply this mechanism in another context. Be creative ! :)
First thing to do, it's to create the Interceptor(s) you need. Remember, Interceptor is designed to be used to intercept the input object and/or the output object. Group your Interceptors by concern and avoid duplicated ones
To do so, you just have to conform to the protocol Interceptor:
protocol Interceptor {
associatedtype Input
func intercept(chain: InterceptorChain<Input>) -> Observable<Input>
}
Intercept the 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)
}
}
When you have your interceptors implemented, it's finished !
To launch the process:
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)
}
For more explanations about the interceptor mechanism, don't hesitate to read the documentation in the okhttp wiki. For non-RxSwift fans, you can have a look at the SwiftInterceptor implementation without any dependencies.