1
votes

I have a static function calling a network service. When the 400 response code happens I would like to redo the network call.

The current code is working, except that the refreshToken in the header does not update between one try and another.

I think that the problem is because the Observable created but the request function does not update at the retry.

I rode on the web that I should use a deferred method on the Observable, but I don't know how.

I've tried moving the code: headers = [HeaderKeys.refreshToken.rawValue: "test test"] anywhere but still it never makes a call with the "test test" refresh token. it always uses the old one.

How can I fix this?

 static func getAccessToken() -> Observable<GetAccessTokenResponse> {
            var retryCounter = 0
        let maxRetryCounter = 3
        let delayRetry = 10.0

        guard let refreshToken = NetworkHelper.shared.refreshToken else {
            return Observable.error(AuthenticationError.networkError)
        }

        var headers = [HeaderKeys.refreshToken.rawValue: refreshToken]


        return NetworkHelper.shared
            .request(url: CoreAPI.accessToken.url, request: nil, headers: headers, responseType: GetAccessTokenResponse.self, method: .get, encoding: nil)
            .catchError({ (error) -> Observable<(GetAccessTokenResponse?, Int)> in
                return Observable.error(AuthenticationError.networkError)
            })
            .flatMap({ (response) -> Observable<GetAccessTokenResponse> in
                // check http status code
                switch response.1 {
                case 200:
                    guard response.0?.accessToken != nil else {
                        return Observable.error(AuthenticationError.genericError)
                    }
                    // success
                    return Observable.just(response.0!)
                case 400:
                    // invalid parameters, refresh token not existing
                    return Observable.error(AuthenticationError.invalidParameters)
                case 404:
                    // user not existing
                    return Observable.error(AuthenticationError.userDoesntExist)
                default:
                    // by default return network error
                    return Observable.error(AuthenticationError.networkError)
                }
            })
            .retryWhen({ (errors) -> Observable<Void> in
                return errors
                    .do(onNext: { (error) in
                        headers = [HeaderKeys.refreshToken.rawValue: "test test"]
                    })
                    .flatMap({error -> Observable<Int> in
                        debugLog("Retrying get refresh token")
                        if retryCounter >= maxRetryCounter {
                            let authError = error as? AuthenticationError ?? .genericError
                            if authError == AuthenticationError.invalidParameters {
                                // publish logged false on subject
                                VDAAuthenticationManager.shared.logged.onNext(false)
                            }
                            return Observable.error(error)
                        }
                        // increase the retry counter and retry
                        retryCounter += 1
                        return Observable<Int>.timer(delayRetry, scheduler: MainScheduler.instance)
                })
                .flatMap ({ (_) -> Observable<Void> in
                    return Observable.just(())
                })
            })
    }
1

1 Answers

2
votes

In the article RxSwift and Retrying a Network Request Despite Having an Invalid Token I explain how to keep and update a token and how to handle retries when you get a 401 error. Using deferred is part of the answer.

In your particular case. It looks like you could use my service like this:

func getToken(lastResponse: GetAccessTokenResponse?) -> Observable<(response: HTTPURLResponse, data: Data)> {
    guard let refreshToken = lastResponse?.refreshToken else { return Observable.error(AuthenticationError.networkError) }
    var request = URLRequest(url: CoreAPI.accessToken.url)
    request.addValue(refreshToken, forHTTPHeaderField: HeaderKeys.refreshToken.rawValue)
    return URLSession.shared.rx.response(request: request)
}

func extractToken(data: Data) throws -> GetAccessTokenResponse {
    return try JSONDecoder().decode(GetAccessTokenResponse.self, from: data)
}

let tokenService = TokenAcquisitionService(initialToken: nil, getToken: getToken, extractToken: extractToken(data:))

In the above, you will have to pass a valid initialToken instead of nil or you will have to modify the getToken so it can get a token even if it doesn't have a refresh token.

An example of how to use deferred is below:

let response = Observable
    .deferred { tokenAcquisitionService.token.take(1) }
    .flatMap { makeRequest(withToken: $0) }
    .map { response in
        guard response.response.statusCode != 401 else { throw ResponseError.unauthorized }
        return response
    }
    .retryWhen { $0.renewToken(with: tokenAcquisitionService) }

I explain in the article what each line of code is for and how it works.