重试延迟 - RxSwift
Posted
技术标签:
【中文标题】重试延迟 - RxSwift【英文标题】:Delay for Retry - RxSwift 【发布时间】:2016-11-25 05:51:39 【问题描述】:有没有优雅的解决方案来为retry
创建延迟?发生错误时,我想等待 5 秒并重新启动 Observable (retry
)
【问题讨论】:
【参考方案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
【讨论】:
【参考方案2】:只需创建一个环绕 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)
【讨论】:
以上是关于重试延迟 - RxSwift的主要内容,如果未能解决你的问题,请参考以下文章
URLSession dataTaskPublisher 在特定错误延迟后重试