本文介绍了RXSwift:如果请求在retryWhen中失败,则修改URLRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当请求失败时,我需要修改请求的标头,但是当我在retryWhen

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

这是我的实现方式

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)
}

如果我po localRequest在设置头文件someKey之后,它将显示我的更改,但是如果我po request在请求函数中,则请求保持不变,没有任何更改.你们都知道我该怎么做才能更改retryWhen中的请求吗?

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 ?

非常感谢您的帮助.

推荐答案

功能性反应式编程是功能性范例.您不必更改请求",而必须生成一个新请求.我会这样写:

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)
}

这篇关于RXSwift:如果请求在retryWhen中失败,则修改URLRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:01