Created
January 6, 2017 21:11
-
-
Save mminer/8e7ba6acb4b5a6105470c57314b71f0d to your computer and use it in GitHub Desktop.
Example of Alamofire RxSwift response serialization extension.
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 Alamofire | |
import RxSwift | |
extension Request: ReactiveCompatible {} | |
extension Reactive where Base: DataRequest { | |
func responseJSON() -> Observable<Any> { | |
return Observable.create { observer in | |
let request = self.base.responseJSON { response in | |
switch response.result { | |
case .success(let value): | |
observer.onNext(value) | |
observer.onCompleted() | |
case .failure(let error): | |
observer.onError(error) | |
} | |
} | |
return Disposables.create(with: request.cancel) | |
} | |
} | |
} | |
// Example usage: | |
_ = Alamofire.request("https://httpbin.org/get").rx.responseJSON() | |
.map { value in | |
let json = value as? [String: Any] ?? [:] | |
let origin = json["origin"] as? String ?? "unknown" | |
return origin | |
} | |
.subscribe(onNext: { print("Origin:", $0) }) |
map
would be skipped entirely and you would need to handle the error case by supplying an onError
handler.
_ = Alamofire.request("https://httpbin.org/get").rx.responseJSON()
.map { ... }
.subscribe(
onNext: { print("Origin:", $0) },
onError: { print("Received error:", $0) }
)
The downside is that onError
lacks the body of the response, which is problematic if you want to parse it. If you require this, you need to change the argument passed to observer.onError
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How would the map work in an error case?