-
-
Save bear2u/39d214b3852731ac38e9377e67850a5a to your computer and use it in GitHub Desktop.
RxAlamofire+ObjectMapper
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
import UIKit | |
import RxSwift | |
import RxAlamofire | |
import ObjectMapper | |
class Post: Mappable { | |
var id: Int = 0 | |
var title: String = "" | |
required init?(_ map: Map) { | |
} | |
func mapping(map: Map) { | |
id <- map["id"] | |
title <- map["title"] | |
} | |
} | |
extension ObservableType { | |
public func mapObject<T: Mappable>(type: T.Type) -> Observable<T> { | |
return flatMap { data -> Observable<T> in | |
let json = data as? AnyObject | |
guard let object = Mapper<T>().map(json) else { | |
throw NSError( | |
domain: "", | |
code: -1, | |
userInfo: [NSLocalizedDescriptionKey: "ObjectMapper can't mapping"] | |
) | |
} | |
return Observable.just(object) | |
} | |
} | |
public func mapArray<T: Mappable>(type: T.Type) -> Observable<[T]> { | |
return flatMap { data -> Observable<[T]> in | |
let json = data as? AnyObject | |
guard let objects = Mapper<T>().mapArray(json) else { | |
throw NSError( | |
domain: "", | |
code: -1, | |
userInfo: [NSLocalizedDescriptionKey: "ObjectMapper can't mapping"] | |
) | |
} | |
return Observable.just(objects) | |
} | |
} | |
} | |
class ViewController: UIViewController { | |
var disposeBag: DisposeBag = DisposeBag() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
JSON(.GET, "http://jsonplaceholder.typicode.com/posts").mapArray(Post.self).subscribeNext { (posts) in | |
for post in posts { | |
print(post.title) | |
} | |
}.addDisposableTo(disposeBag) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment