Last active
February 19, 2020 11:43
-
-
Save darrarski/2b054418b00bdcae449a1d824d1bef32 to your computer and use it in GitHub Desktop.
RxSwift Observable Retry When with Count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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