Moya支持Combine框架
这是Moya的README
Moya与Combine的简单使用
@State private var cancellables: Set<AnyCancellable> = []
let provider = MoyaProvider<GitHub>()
provider
.requestPublisher(.zen, callbackQueue: callbackQueue)
.sink { completion in
print("completion: ", completion)
} receiveValue: { response in
print("data: ", response)
}.store(in: &cancellables)
与SwiftJSON的配合使用
增加扩展方案
extension AnyPublisher where Output == Response, Failure == MoyaError {
func mapSwiftJSON(failsOnEmptyData: Bool = true) -> AnyPublisher<JSON, MoyaError> {
let result = self.mapJSON(failsOnEmptyData: failsOnEmptyData)
return result.tryMap({JSON($0)}).mapError{ error -> MoyaError in
if let moyaError = error as? MoyaError {
return moyaError
} else {
return .underlying(error, nil)
}
}.eraseToAnyPublisher()
}
}
使用
@State private var cancellables: Set<AnyCancellable> = []
let provider = MoyaProvider<GitHub>()
provider
.requestPublisher(.zen, callbackQueue: callbackQueue)
.mapSwiftJSON() // 同样是在数据流中进行处理,跟Moya与rx扩展类似
.sink { completion in
print("completion: ", completion)
} receiveValue: { response in
// 这里的response就是swiftyJSON中的JSON结构体格式了
print("data: ", response)
}.store(in: &cancellables)