内容概览
- Moya
- RxSwift
- 实例讲解
- 总结
Moya
- TargetType
/// The protocol used to define the specifications necessary for a `MoyaProvider`.
public protocol TargetType {
/// The target's base `URL`.
var baseURL: URL {
get }
/// The path to be appended to `baseURL` to form the full `URL`.
var path: String {
get }
/// The HTTP method used in the request.
var method: Moya.Method {
get }
/// Provides stub data for use in testing.
var sampleData: Data {
get }
/// The type of HTTP task to be performed.
var task: Task {
get }
/// The type of validation to perform on the request. Default is `.none`.
var validationType: ValidationType {
get }
/// The headers to be used in the request.
var headers: [String: String]? {
get }
}
在遵循这个协议的类型中提供这些属性,可以很方便地定制API请求的各种参数。
而且,由于是属性,所以非常容易进行测试。
- MoyaProvider
/// Request provider class. Requests should be made through this class only.
open class MoyaProvider<Target: TargetType>: MoyaProviderType {
/// Closure that defines the endpoints for the provider.
public typealias EndpointClosure = (Target) -> Endpoint
/// Closure that decides if and what request should be performed.
public typealias RequestResultClosure = (Result<URLRequest, MoyaError>) -> Void
/// Closure that resolves an `Endpoint` into a `RequestResult`.
public typealias RequestClosure = (Endpoint, @escaping RequestResultClosure) -> Void
/// Closure that decides if/how a request should be stubbed.
public typealias StubClosure = (Target) -> Moya.StubBehavior
/// A closure responsible for mapping a `TargetType` to an `EndPoint`.
public let endpointClosure: EndpointClosure
/// A closure deciding if and what request should be performed.
public let requestClosure: RequestClosure
/// A closure responsible for determining the stubbing behavior
/// of a request for a given `TargetType`.
public let stubClosure: StubClosure
...
/// Initializes a provider.
public init(endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping,
requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping,
stubClosure: @escaping StubClosure = MoyaProvider.neverStub,
callbackQueue: DispatchQueue? = nil,
manager: Manager = MoyaProvider<Target>.defaultAlamofireManager(),
plugins: [PluginType] = [],
trackInflights: Bool = false) {
self.endpointClosure = endpointClosure
self.requestClosure = requestClosure
self.stubClosure = stubClosure
self.manager = manager
self.plugins = plugins
self.trackInflights = trackInflights
self.callbackQueue = callbackQueue
}
...
}
实际的请求由MoyaProvider
发起,而实例化一个MoyaProvider
需要提供一个泛型参数Target
。
所以MoyaProvider
需要相应的TargetType
,然后才能完成请求。
在进行测试的时候,我们可以使用这些Closure
去深度定制MoyaProvider
实例以实现我们想要的效果。