Skip to content

Instantly share code, notes, and snippets.

@kciter
Created August 11, 2016 02:52
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kciter/e6f13119cbf8ad0963a68a5ebc421069 to your computer and use it in GitHub Desktop.
Save kciter/e6f13119cbf8ad0963a68a5ebc421069 to your computer and use it in GitHub Desktop.
RxAlamofire+ObjectMapper
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)
}
}
@prgorasiya
Copy link

Do you have any idea about how to use ObjectMapper with Bond?
For example :
import ObjectMapper

struct DetailsV2Model: Mappable {
    var Info: InfoModel!
    var location: LocationModel!

    mutating func mapping(map: Map) {
        Info <- map["Info"]
        location <- map["location"]
    }
    
    
    init?(map: Map) {
        
    }
}

When I try to use this in my ViewModal class, i get following error.

let detailsModel = Observable<DetailsV2Model?>(DetailsV2Model())

Missing argument for parameter 'map' in call

Cant really use like this
let detailsModel = Observable<DetailsV2Model?>(DetailsV2Model(map: <#Map#>))

@hardikamal
Copy link

@prgorasiya any solution found to this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment