简体   繁体   English

RxAlamofire:重试当进入订阅块时

[英]RxAlamofire: retryWhen drops into subscribe block

I'm trying to implement an alamofire call with max retries. 我正在尝试使用max retries实现alamofire调用。 Code is below: 代码如下:

RxAlamofire.request(.post, URL, parameters: parameters, encoding: JSONEncoding.default)
    .observeOn(MainScheduler.instance)
    .retryWhen { (errors: Observable<Error>) in
        return errors.flatMapWithIndex { (e, a) -> Observable<Int64> in
            if a >= self.RETRY_COUNT - 1 {
                return Observable.error(e)
            }
            print("Error: delay server call retry by \(a+1) second(s)")
            return Observable<Int64>.timer(RxTimeInterval(a+1), scheduler: MainScheduler.instance)
        }
    }
    .subscribe(
        onNext: {
            (result) in

            print("I get here when retrying...")
        },
        onError: { (error) in
            print(error)
        }
    )
    .addDisposableTo(self.disposeBag)

Unfortunately, on retrying, I get into the onNext block in subscribe - I don't want to get there until I have a result. 不幸的是,在重试时,我进入了订阅中的onNext块 - 我不希望到达那里直到我得到结果。 (The onError gives an error after max retries is exceeded as expected). (按预期超出最大重试次数后,onError会出错)。 Please can someone help? 请有人帮忙吗?

I have tried to reproduce your scenario, but the following code does not trigger the onNext closure in the subscription upon an error. 我试图重现您的方案,但以下代码在出错时不会触发订阅中的onNext闭包。 I have rewritten your code slightly, my example always errors out. 我稍微重写了你的代码,我的例子总是出错。 I am using RxSwift 4.0.0. 我正在使用RxSwift 4.0.0。

let count = 2

enum MyError: Error {
    case crash
}

_ = Observable<Int>.error(MyError.crash)
    .debug("prior")
    .retryWhen { errors in
        return errors.enumerated().flatMap { (index, error) -> Observable<Void> in
            guard index < count - 1 else { return .error(error) }

            print("Error: delay server call retry by \(index + 1) second(s)")
            return Observable<Void>.just(()).delay(RxTimeInterval(index + 1), scheduler: MainScheduler.instance)
        }
    }
    .debug("after")
    .subscribe(onNext: { element in
        print("got next element: \(element)")
    })

This results in the following output. 这导致以下输出。

2018-03-16 09:05:16.921: after -> subscribed 2018-03-16 09:05:16.924: prior -> subscribed 2018-03-16 09:05:16.924: prior -> Event error(blok) Error: delay server call retry by 1 second(s) 2018-03-16 09:05:16.925: prior -> isDisposed 2018-03-16 09:05:17.926: prior -> subscribed 2018-03-16 09:05:17.926: prior -> Event error(blok) 2018-03-16 09:05:17.927: after -> Event error(blok) 2018-03-16 09:05:17.928: after -> isDisposed 2018-03-16 09:05:17.928: prior -> isDisposed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM