Created
April 14, 2017 07:01
-
-
Save laiso/29654ba0d562c86234a0a0d78f080684 to your computer and use it in GitHub Desktop.
RxSwift(RxCocoa)+APIKit+Himotoki
This file contains hidden or 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
import RxSwift | |
import RxCocoa | |
import APIKit | |
extension Reactive where Base: URLSession { | |
func response<T: Request>(_ request: T) -> Observable<T.Response> { | |
var req: URLRequest | |
do { | |
req = try request.buildURLRequest() | |
} catch { | |
return .error(error) | |
} | |
return self.response(request: req) | |
.map { response, data in | |
try request.parse(data: data, urlResponse: response) | |
} | |
} | |
} |
This file contains hidden or 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
import RxSwift | |
import RxCocoa | |
import APIKit | |
import Himotoki | |
let request = SearchRepositoriesRequest(query: "swift") | |
let repositories = URLSession.shared.rx.response(request) | |
.map { | |
$0.map { repo in print(repo.name) } | |
} | |
// MARK; Implementation | |
struct Repository: Decodable { | |
let id: Int64 | |
let name: String | |
static func decode(_ e: Extractor) throws -> Repository { | |
return try Repository( | |
id: e.value("id"), | |
name: e.value("name")) | |
} | |
} | |
struct SearchRepositoriesRequest: Request { | |
let query: String | |
typealias Response = [Repository?] | |
var baseURL: URL { | |
return URL(string: "https://api.github.com")! | |
} | |
var method: HTTPMethod { | |
return .get | |
} | |
var path: String { | |
return "/search/repositories" | |
} | |
var parameters: Any? { | |
return ["q": query] | |
} | |
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> [Repository?] { | |
return try decodeArray(object) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment