Forked from billwang1990/ObjectMapper+Alamofire+RxSwift
Last active
June 21, 2016 22:05
-
-
Save tangzhen/5c7712cea0d69fc57254825a1ea869e2 to your computer and use it in GitHub Desktop.
ObjectMapper+Alamofire+RxSwift
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
// | |
// RxAlamofireObjectMapper.swift | |
// | |
// Edit by TangZhen on 06/19/16. | |
// Forked from https://gist.github.com/billwang1990/a0e20919e7add7aafd8e | |
// Copyright © 2016 ztang.pub All rights reserved. | |
// | |
import Foundation | |
import Alamofire | |
import ObjectMapper | |
import RxSwift | |
public enum ObjectMapError: ErrorType { | |
case MapError(AnyObject?) | |
} | |
extension Alamofire.Request { | |
func processMap<N>(map: (AnyObject) -> N?) -> Observable<N> { | |
return Observable.create { (observer: AnyObserver<N>) -> Disposable in | |
self.response(responseSerializer: Request.JSONResponseSerializer(options: NSJSONReadingOptions.AllowFragments), | |
completionHandler: { (response) -> Void in | |
let result = response.result | |
if result.isSuccess { | |
guard let obj = map(result.value!) else { | |
observer.on(Event.Error(ObjectMapError.MapError(result.value))) | |
return | |
} | |
observer.on(Event.Next(obj)) | |
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