Skip to content

Instantly share code, notes, and snippets.

@darrarski
Last active February 19, 2020 11:43
Show Gist options
  • Save darrarski/2b054418b00bdcae449a1d824d1bef32 to your computer and use it in GitHub Desktop.
Save darrarski/2b054418b00bdcae449a1d824d1bef32 to your computer and use it in GitHub Desktop.
RxSwift Observable Retry When with Count
extension ObservableType {
func retry(_ maxAttemptCount: Int = 1, when: @escaping (Error) -> Observable<Void>) -> Observable<E> {
return retryWhen { errorObservable -> Observable<Void> in
var retries = maxAttemptCount
return errorObservable.flatMap { error -> Observable<Void> in
guard retries > 0 else { return Observable.error(error) }
retries -= 1
return when(error)
}
}
}
}
// Example usage:
func fetchSomething() -> Observable<String> { ... }
fetchSomething()
.retry(2, when: { error -> Observable<Void> in
print("^^^ RETRYING AFTER ERROR: \(error)")
return Observable.just(()) // just retry
})
.subscribe(
onNext: { print("^^^ NEXT: \($0)") },
onError: { print("^^^ ERROR: \($0)" )},
onCompleted: { print("^^^ COMPLETED") },
onDisposed: { print("^^^ DISPOSED") }
)
.disposed(by: disposeBag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment