问题
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