为retry
创建延迟是否有优雅的解决方案?发生错误时,我想等待5秒钟并重新启动Observable(retry
)
答案 0 :(得分:1)
这是Swift 4.0+的代码
// sample retry function with delay
private func sampleRetryWithDelay() {
let maxRetry = 3
let retryDelay = 1.0 // seconds
let _ = sampleStreamWithErrors() // sample observable stream, replace with the required observable
.retryWhen { errors in
return errors.enumerated().flatMap { (index, error) -> Observable<Int64> in
return index <= maxRetry ? Observable<Int64>.timer(RxTimeInterval(retryDelay), scheduler: MainScheduler.instance) : Observable.error(error)
}
}.subscribe(onNext: {value in
print("Result:\(value)")
})
}
// Sample stream with errors, helper function only - generating errors 70% of the time
private func sampleStreamWithErrors() -> Observable<Int> {
return Observable.create { observer in
let disposable = Disposables.create() {} // nothing to cancel, we let it complete
let randomInt = Int(arc4random_uniform(100) + 1)
if randomInt > 70 {
observer.on(.next(randomInt))
observer.on(.completed)
} else {
let sampleError = NSError(domain: "SampleDomain", code: randomInt, userInfo: nil)
print("Result:Error:\(randomInt)")
observer.on(.error(sampleError))
}
return disposable
}
}
答案 1 :(得分:0)
只需创建环绕retry()
的PrimitiveSequence扩展即可。
(Swift5.1 RxSwift 4.3.1)
extension PrimitiveSequence {
func retry(maxAttempts: Int, delay: TimeInterval) -> PrimitiveSequence<Trait, Element> {
return self.retryWhen { errors in
return errors.enumerated().flatMap { (index, error) -> Observable<Int64> in
if index <= maxAttempts {
return Observable<Int64>.timer(RxTimeInterval(delay), scheduler: MainScheduler.instance)
} else {
return Observable.error(error)
}
}
}
}
}
用法示例:(重试3次,每次延迟2秒)
yourRxStream.retry(maxAttempts: 3, delay: 2)