c8112002
c8112002

Reputation: 385

Rxswift + Moya + Moya-ObjectMapper Error handling

I am using Moya and Moya-ObjectMapper with Rxswift to make network requests.

My network request is below.

let provider = RxMoyaProvider<APIClient>()

requestHospitalButton.rx_tap
    .withLatestFrom(hospitalCode)
    .flatMapLatest { [unowned self] code in
        self.provider.request(.Hospital(code: code))
     }
     .mapObject(Hospital)
     .subscribe { [unowned self] event in
         switch event {
         case .Next(let hospital):
             // success
         case .Error(let error):
             // error
         default: break
         }
     }
     .addDisposableTo(rx_disposeBag)

If the error occurs, then my hospital request Observable terminates and I can never make my hospital request again.

How can I retry my hospital request when the requestHospitalButton is tapped?

Upvotes: 1

Views: 1459

Answers (1)

solidcell
solidcell

Reputation: 7729

You should use retryWhen, which is documented here:

extension ObservableType {

    /**
    Repeats the source observable sequence on error when the notifier emits a next value.
    If the source observable errors and the notifier completes, it will complete the source sequence.
    - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)

    - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
    - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
    */
    public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
        -> Observable<E> {
            return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler)
    }
}

Upvotes: 1

Related Questions