RXSwift: Modifying URLRequest if request fails in `retryWhen`

强颜欢笑 提交于 2019-12-13 03:37:20

问题


I need to modify the headers of the request when the request fails but the request doesn't change when I modify the request in retryWhen

Here is my implementation:

func makeRequest(serviceRequest: URLRequest) {
    let maxRetry = 2
    var localRequest = serviceRequest
    request(request: localRequest).retryWhen { errors in
        return errors.enumerated().flatMap { (arg) -> Observable<Int64> in
            localRequest.setValue("someValue", forHTTPHeaderField: "someKey")

            let (index, error) = arg
            return index <= maxRetry ? Observable<Int64>.timer(DispatchTimeInterval.microseconds(4),
                                                               scheduler: MainScheduler.instance) : Observable.error(error)
        }
    }.subscribe(onNext:{ result in
        print(result)

        }).disposed(by: disposeBag)
}

If I po localRequest after set headers someKey it would show my changes but if I po request in the request function the request remains the same with no changes. Any of you knows what can I do to changes the request in the retryWhen ?

I'll really appreciate your help.


回答1:


Functional Reactive Programming is a functional paradigm. You don't "change the Request" you have to generate a new request. I would write it more like this:

func makeRequest(buildRequest: @escaping (String) -> URLRequest) {
    Observable.deferred {
        request(request: buildRequest(token))
    }
    .retryWhen { (error) in
        error.enumerated().flatMap { (index, error) -> Observable<Void> in
            token = "some value"
            return index <= 2 ?
                Observable.just(()).delay(.microseconds(4), scheduler: MainScheduler.instance) :
                Observable.error(error)
        }
    }
    .subscribe(onNext:{ result in
        print(result)
    })
    .disposed(by: disposeBag)
}


来源:https://stackoverflow.com/questions/59188451/rxswift-modifying-urlrequest-if-request-fails-in-retrywhen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!