Created
August 11, 2016 02:52
-
-
Save kciter/e6f13119cbf8ad0963a68a5ebc421069 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
Do you have any idea about how to use ObjectMapper with Bond?
For example :
import ObjectMapper
When I try to use this in my ViewModal class, i get following error.
Cant really use like this
let detailsModel = Observable<DetailsV2Model?>(DetailsV2Model(map: <#Map#>))