Created
October 11, 2017 14:09
-
-
Save jonasz-baron/5379c2a32198f1ed4224167ba053f9af to your computer and use it in GitHub Desktop.
RxAlamofire usage with Codable protocol for object mapping. Inspired by: https://gist.github.com/kciter/e6f13119cbf8ad0963a68a5ebc421069
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
// Model | |
import Foundation | |
class Post: Codable { | |
var id = 0 | |
var userId = 0 | |
var title = "" | |
var body = "" | |
} | |
// ObservableType Extension | |
import RxSwift | |
extension ObservableType { | |
public func mapObject<T: Codable>(type: T.Type) -> Observable<T> { | |
return flatMap { data -> Observable<T> in | |
let responseTuple = data as? (HTTPURLResponse, Data) | |
guard let jsonData = responseTuple?.1 else { | |
throw NSError( | |
domain: "", | |
code: -1, | |
userInfo: [NSLocalizedDescriptionKey: "Could not decode object"] | |
) | |
} | |
let decoder = JSONDecoder() | |
let object = try decoder.decode(T.self, from: jsonData) | |
return Observable.just(object) | |
} | |
} | |
public func mapArray<T: Codable>(type: T.Type) -> Observable<[T]> { | |
return flatMap { data -> Observable<[T]> in | |
let responseTuple = data as? (HTTPURLResponse, Data) | |
guard let jsonData = responseTuple?.1 else { | |
throw NSError( | |
domain: "", | |
code: -1, | |
userInfo: [NSLocalizedDescriptionKey: "Could not decode object"] | |
) | |
} | |
let decoder = JSONDecoder() | |
let objects = try decoder.decode([T].self, from: jsonData) | |
return Observable.just(objects) | |
} | |
} | |
} | |
// View controller | |
import UIKit | |
import RxSwift | |
import RxAlamofire | |
class ViewController: UIViewController { | |
let disposeBag = DisposeBag() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
RxAlamofire.requestData(.get, "https://jsonplaceholder.typicode.com/posts") | |
.mapArray(type: Post.self) | |
.subscribe(onNext: { posts in | |
_ = posts.map { print($0.title) } | |
}) | |
.disposed(by: disposeBag) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment