Skip to content

Instantly share code, notes, and snippets.

@mecid
Created June 19, 2019 12:08
Show Gist options
  • Save mecid/b2dac712138b95fb9ad2ce11dbb1bb74 to your computer and use it in GitHub Desktop.
Save mecid/b2dac712138b95fb9ad2ce11dbb1bb74 to your computer and use it in GitHub Desktop.
Combine in action post's source code
import Foundation
import Combine
struct Repo: Decodable {
var id: Int
let owner: Owner
let name: String
let description: String
struct Owner: Decodable {
let avatar: URL
enum CodingKeys: String, CodingKey {
case avatar = "avatar_url"
}
}
}
struct SearchResponse: Decodable {
let items: [Repo]
}
class GithubService {
private let session: URLSession
private let decoder: JSONDecoder
init(session: URLSession = .shared, decoder: JSONDecoder = .init()) {
self.session = session
self.decoder = decoder
}
}
extension GithubService {
func search(matching query: String) -> AnyPublisher<[Repo], Error> {
guard
let url = URL(string: "https://api.github.com/search/repositories?q=\(query)")
else { preconditionFailure("Can't create url for query: \(query)") }
return session.dataTaskPublisher(for: url)
.map { $0.data }
.decode(type: SearchResponse.self, decoder: decoder)
.map { $0.items }
.eraseToAnyPublisher()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment