Skip to content

Instantly share code, notes, and snippets.

@AquaGeek
Last active February 6, 2017 11:27
Show Gist options
  • Save AquaGeek/c05db8fa6586cbd05c27 to your computer and use it in GitHub Desktop.
Save AquaGeek/c05db8fa6586cbd05c27 to your computer and use it in GitHub Desktop.
RxSwift
// Retry with backoff
// Adapted from http://blog.danlew.net/2016/01/25/rxjavas-repeatwhen-and-retrywhen-explained/
Observable
.range(start: 1, count: 10)
.doOn(onNext: { i in
if i == 5 {
throw NSError(domain: "com.example", code: 1, userInfo: ["any": "thing"])
}
})
.retryWhen { (attempts: Observable<ErrorType>) -> Observable<Int64> in
attempts.doOn({ (event) -> Void in
print("Attempt: \(attempts)")
})
return Observable
.zip(attempts, Observable.range(start: 1, count: 3), resultSelector: { (o1, o2) in
return o2
})
.flatMap({ i -> Observable<Int64> in
print("Delay retry by \(i) seconds")
return Observable.timer(RxTimeInterval(i), period: 0.0, scheduler: MainScheduler.instance)
})
}
.distinctUntilChanged()
.take(10)
.subscribe { (event) in
print("Event: \(event)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment