-1
extension URLSession {
    fileprivate func loadRepositories(resource: URL) -> Observable<SearchRepositoriesResponse> {
        return self
            .rx.response(request: URLRequest(url: resource))
            .retry(3)
            .map(Repository.parse)
            .retryWhen { $0.delay(1.0, scheduler: MainScheduler.instance) }
    }
}

Why should I use retryWhen { $0.delay(1.0, scheduler: MainScheduler.instance) } at the last step? What happens if I do not use it?

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
NVXA
  • 11
  • 2

1 Answers1

0

If Repository.parse returns an error, the retryWhen in your code example delays the error emission by 1 second. IMHO the use of retryWhen operator is a bit misleading in this case, because there is no retry happening. It just delays the error.

The example code on RxFeedback's github page has been updated to a new version that actually does retries until a maximum number of attempts is reached:

extension URLSession {
    fileprivate func loadRepositories(resource: URL) -> Observable<SearchRepositoriesResponse> {

        // The maximum number of attempts to retry before launch the error
        let maxAttempts = 4

        return self
            .rx
            .response(request: URLRequest(url: resource))
            .retry(3)
            .map(Repository.parse)
            .retryWhen { errorTrigger in
                return errorTrigger.flatMapWithIndex { (error, attempt) -> Observable<Int> in
                    if attempt >= maxAttempts - 1 {
                        return Observable.error(error)
                    }

                    return Observable<Int>
                        .timer(Double(attempt + 1), scheduler: MainScheduler.instance).take(1)
                }
        }
    }
}

Now, when Repository.parse returns an error, retryWhen causes a retry when the maximum number of attempts has not been reached. The retry has a delay which becomes longer with every attempt. When the maximum number of attempts is reached it emits an error and finishes the main sequence with an error.

joern
  • 27,354
  • 7
  • 90
  • 105