-
-
Save ahmdmau/f5693612820285f1941879dcb9b44015 to your computer and use it in GitHub Desktop.
Example of Alamofire RxSwift response serialization extension.
This file contains hidden or 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) }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment