Skip to content

Instantly share code, notes, and snippets.

@mminer
Created January 6, 2017 21:11
Show Gist options
  • Save mminer/8e7ba6acb4b5a6105470c57314b71f0d to your computer and use it in GitHub Desktop.
Save mminer/8e7ba6acb4b5a6105470c57314b71f0d to your computer and use it in GitHub Desktop.
Example of Alamofire RxSwift response serialization extension.
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) })
@mminer
Copy link
Author

mminer commented Oct 17, 2017

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