Combine examples

This commit is contained in:
John Holdsworth
2019-07-10 00:37:46 +01:00
parent f5f4d0b3d5
commit 8018d0c2a0
13 changed files with 274 additions and 91 deletions

View File

@@ -10,27 +10,42 @@ import Combine
import Foundation
enum RepositoryAPI {
typealias SearchResponse = AnyPublisher<Result<[Repository], ErrorResponse>, Never>
typealias SendRequest = (URLRequest) -> AnyPublisher<Data, URLSessionError>
static func search(query: String) -> AnyPublisher<[Repository], Error> {
static func search(query: String) -> SearchResponse {
search(query: query, sendRequest: URLSession.shared.combine.send)
}
static func search(query: String, sendRequest: SendRequest) -> SearchResponse {
guard var components = URLComponents(string: "https://api.github.com/search/repositories") else {
return Publishers.Empty<[Repository], Error>().eraseToAnyPublisher()
return .empty()
}
components.queryItems = [URLQueryItem(name: "q", value: query)]
guard let url = components.url else {
return Publishers.Empty<[Repository], Error>().eraseToAnyPublisher()
return .empty()
}
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return URLSession.shared.combine.send(request: request)
return sendRequest(request)
.decode(type: ItemResponse<Repository>.self, decoder: decoder)
.map { $0.items }
.handleEvents(receiveOutput: { print($0) },
receiveCompletion: { print($0)})
.map { Result<[Repository], ErrorResponse>.success($0.items) }
.catch { error -> SearchResponse in
guard case let .serverErrorMessage(_, data)? = error as? URLSessionError else {
return .just(.success([]))
}
do {
let response = try JSONDecoder().decode(ErrorResponse.self, from: data)
return .just(.failure(response))
} catch _ {
return .just(.success([]))
}
}
.eraseToAnyPublisher()
}
}