Reputation: 4530
Following is my code to do RxAlamofire requests
RxAlamofire.request(request as URLRequestConvertible).validate(statusCode: 200..<300).responseJSON().asObservable()
.subscribe(onNext: { [weak self] (response) in
if let json = response.data {
let jsonResult = JSON(json)
let foodMenuResult = MenuResult(jsonResult)
self?.delegate?.showMenu(menuResult: foodMenuResult)
}
}, onError: { [weak self] (error) in
// print(error.localizedDescription)
UIViewController().logAPIError(error: error)
self?.delegate?.onError(MenuViewController.REQUEST_MENU)
},onCompleted: {})
.disposed(by: disposeBag)
I want to write extension related to Observable so that I can handle error at one place instead of writing same code on every onError
How can I do this?
Upvotes: 1
Views: 547
Reputation: 33967
Here's the most obvious solution:
func myRequest(_ request: URLRequestConvertable) -> Observable<T> {
return RxAlamofire.request(request as URLRequestConvertible)
.validate(statusCode: 200..<300)
.responseJSON()
.asObservable()
.do(onError: { /* do the thing you want to always do */ })
}
I don't use alamofire, but replace T
in the above with whatever type the code emits.
Upvotes: 1