Last active
June 20, 2019 10:56
-
-
Save deda9/ce40d242fe54c2695248cff2f86cc57a to your computer and use it in GitHub Desktop.
How to chain two network requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typealias RequestChainable<T: Codable> = (request: URLRequestBuilder, model: T.Type) | |
extension NetworkService { | |
func chain<T, U>(_ r: RequestChainable<T>, _ r2: RequestChainable<U>, completion: @escaping (Result<(T?, U?)>) -> Void) { | |
self.execute(r.request, model: r.model) { res in | |
switch res { | |
case .success(let value): completion(Result.success((value, nil))) | |
case .failure: | |
self.execute(r2.request, model: r2.model, completion: { result in | |
switch result { | |
case .success(let value): completion(Result.success((nil, value))) | |
case .failure(let error): completion(Result.failure(error)) | |
} | |
}) | |
} | |
} | |
} | |
func chainx<T>(_ reqs: RequestChainable<T>..., completion: @escaping (Result<(T)>) -> Void) { | |
var index = 0 | |
func doReq(index: Int) { | |
let current = reqs[index] | |
self.execute(current.request, model: current.model) { result in | |
switch result { | |
case .success: | |
doReq(index: index + 1) | |
case .failure(let error ): completion(.failure(error)) | |
} | |
} | |
} | |
doReq(index: index) | |
} | |
class Test { | |
func test() { | |
let r1: RequestChainable = (request: UserAPIs.getProfile, model: Token.self) | |
let r2: RequestChainable = (request: UserAPIs.getProfile, model: Token.self) | |
let service = NetworkService() | |
service.chain(r1, r2) { result in | |
switch result { | |
case .success: break | |
case .failure: break | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment