Last active
June 29, 2022 10:36
-
-
Save danielt1263/c455820f7a13a6ae8599efc8113c040f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// | |
// Restart.swift | |
// | |
// Created by Daniel Tartaglia on 23 Jun 2022. | |
// Copyright © 2022 Daniel Tartaglia. MIT License. | |
// | |
import RxSwift | |
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 both errors raised by the | |
source observable along with a count of previous consecutive errors and returns an 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. | |
*/ | |
func restart<TriggerObservable>(when notificationHandler: @escaping (Observable<(Int, Error)>) -> TriggerObservable) -> Observable<Element> | |
where TriggerObservable: ObservableType { | |
let count = BehaviorSubject<Int>(value: 0) | |
return self.do( | |
onNext: { _ in | |
count.onNext(0) | |
}, | |
onError: { _ in | |
count.onNext(try! count.value() + 1) | |
} | |
) | |
.retry { error in | |
notificationHandler(error.withLatestFrom(count) { ($1, $0) }) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment