Skip to content

Instantly share code, notes, and snippets.

@billwang1990
Created October 30, 2015 06:24
Show Gist options
  • Save billwang1990/a0e20919e7add7aafd8e to your computer and use it in GitHub Desktop.
Save billwang1990/a0e20919e7add7aafd8e to your computer and use it in GitHub Desktop.
ObjectMapper+Alamofire+RxSwift
//
// RxAlamofireObjMapper.swift
// RXDemo
//
// Created by Yaqing Wang on 10/30/15.
// Copyright © 2015 billwang1990.github.io. All rights reserved.
//
import Foundation
import Alamofire
import ObjectMapper
import RxSwift
public enum ObjectMapError: ErrorType{
case MapError(AnyObject?)
}
extension Request{
func processMap<N>(map:(AnyObject)->N?) -> Observable<N>{
return create({ (observer) -> Disposable in
self.response(queue: nil, responseSerializer: Request.JSONResponseSerializer(options: NSJSONReadingOptions.AllowFragments), completionHandler:{(request:NSURLRequest?, reponse:NSURLResponse?, result:Result) -> Void in
if result.isSuccess{
guard let o = map(result.value!) else{
observer.on(Event.Error(ObjectMapError.MapError(result.value)))
return
}
observer.on(Event.Next(o))
observer.on(Event.Completed)
}else{
observer.on(Event.Error(result.error!))
}
})
return AnonymousDisposable{
self.cancel()
}
})
}
func rx_responseArray<T:Mappable>(type:T.Type) -> Observable<[T]>{
return self.processMap{ (json) in
Mapper<T>().mapArray(json)
}
}
func rx_responseObject<T:Mappable>(type:T.Type) -> Observable<T>{
return self.processMap{ (json) in
Mapper<T>().map(json)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment