Skip to content

Instantly share code, notes, and snippets.

@danielt1263
Last active June 29, 2022 10:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielt1263/c455820f7a13a6ae8599efc8113c040f to your computer and use it in GitHub Desktop.
Save danielt1263/c455820f7a13a6ae8599efc8113c040f to your computer and use it in GitHub Desktop.
//
// 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