Created
July 23, 2020 01:08
-
-
Save jamesrochabrun/8a31d21b0235065d73ef709691b59dc4 to your computer and use it in GitHub Desktop.
Generic nertworking layer using Combine.
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
// 1 | |
protocol CombineAPI { | |
var session: URLSession { get } | |
func execute<T>(_ request: URLRequest, decodingType: T.Type, queue: DispatchQueue, retries: Int) -> AnyPublisher<T, Error> where T: Decodable | |
} | |
// 2 | |
extension CombineAPI { | |
func execute<T>(_ request: URLRequest, | |
decodingType: T.Type, | |
queue: DispatchQueue = .main, | |
retries: Int = 0) -> AnyPublisher<T, Error> where T: Decodable { | |
/// 3 | |
return session.dataTaskPublisher(for: request) | |
.tryMap { | |
guard let response = $0.response as? HTTPURLResponse, response.statusCode == 200 else { | |
throw APIError.responseUnsuccessful | |
} | |
return $0.data | |
} | |
.decode(type: T.self, decoder: JSONDecoder()) | |
.receive(on: queue) | |
.retry(retries) | |
.eraseToAnyPublisher() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment