Created
October 30, 2015 06:24
-
-
Save billwang1990/a0e20919e7add7aafd8e 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
// | |
// 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