1

Let's say I have an button and every time that button is tapped I would like to perform a network request and bind the results to a view on the main scheduler. I also need to deal with the chance that this network request might fail. Here was my original idea:

button.rx.tap.asObservable()
  .flatMap(networkRequest)
  .asDriver(onErrorRecover: handleError)
  .drive(uiComponent)
  .disposed(by: disposeBag)

What I want to happen is for a possible error to be handled by handleError and then make the request again when the button is tapped again. This does not work because in the event of an error, I am now subscribed to the Driver returned by handleError. The only other idea I have is to keep the signal an Observable and handle the error case and next case separately in the subscribe. This would also necessitate a observeOn. I was hoping for something a bit more elegant than that. Does anyone have an alternative approach to this use case?

Edit

I should also mention that one method that has worked for us was to handle the error in the flatMap.

button.rx.tap.asObservable()
  .flatMap {
    return networkRequest()
      .catchError(handleError)
  }
  .asDriver(onErrorDriveWith: Driver.empty())
  .drive(uiComponent)
  .disposed(by: disposeBag)

However, it again seems less elegant than I would think it should be.

Scott H
  • 1,509
  • 10
  • 14

1 Answers1

0

I will use Result type to wrap the return result and error that may occur.

You can convert to Result type in your networkRequest() method

  • Thanks for your response. However, I believe if we wrap the error in a `Result` it only achieves the same thing as not converting to a `Driver`, and handling the `next` and `error` events differently in subscribing to the `Observable`. – Scott H Feb 24 '17 at 19:36
  • 1
    Yeah I know what you want to achieve but I tried that before but didn't come up with a good solution just like you. I ended up with the `Result` way which looks best to me. I believe there is `onErrorResumeNext` operator which is what we both want but sadly this operator is not available in `RxSwift` – Pitiphong Phongpattranont Feb 24 '17 at 19:44