Followed refresh token strategy from this gist - https://gist.github.com/saroar/ca78de9dc798cdbaaa47791380062596
but couldn't get it working.
Ideal flow - run
function from NetworkAgent
will make a call using the tokenSubject
from Authenticator
. If that call fails with authentication error, refreshToken
function from Authenticator will be called. Now, when this refresh token call gets completed, the tokenSubject
will send a value (check the receiveCompletion block of sink operator in Authenticator
) which NetworkAgent
has already subscribed in run
function. Once the NetworkAgent receives this value from tokenSubject
it will again execute that request in the run
function.
Bug - Once the 401 error is received, the refresh token request is made but after that completes successfully, failed request doesn't get retried. Seems like the value sent by the tokenSubject is not received by the subscriber may be due to some reference issue.
Please find my implementation below: -
This is the Network Agent that makes all the api calls -
class NetworkAgent {
struct Response {
let value: T
let response: URLResponse
}
let authenticator = Authenticator()
func run<T: Decodable>(_ request: URLRequest) -> AnyPublisher<Response<T>, Error> {
let tokenSubject = authenticator.tokenSubject()
// a better way to handle refresh token logic would be to use tryCatch operator suceeded by retry operator
// should be done in one of the upcoming releases
return tokenSubject
.flatMap({ token -> AnyPublisher<Response<T>, Error> in
return URLSession.shared
.dataTaskPublisher(for: request)
.tryMap { [weak self] result -> Response<T> in
self?.logResponse(result.response, request: request, data: result.data)
// check for the response status
if let httpURLResponse = result.response as? HTTPURLResponse {
let networkResponse = APIClient.status(httpURLResponse)
switch networkResponse {
case .success: break
case .failure(let error):
if error == HTTPURLResponseError.authenticationError {
// refresh token logic
if request.url?.absoluteString.contains("/auth/token/refresh") == false {
self?.authenticator.refreshToken(using: tokenSubject)
}
} else {
throw error
}
}
}
// map response and return in case of a successful request
let value = try JSONDecoder().decode(T.self, from: result.data)
return Response(value: value, response: result.response)
}
.retry(3)
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
})
.handleEvents(receiveOutput: { _ in
tokenSubject.send(completion: .finished)
})
.eraseToAnyPublisher()
}
}
And this is the Authenticator class implementation -
class Authenticator {
//MARK:- Properties
private var disposables = Set()
private let queue = DispatchQueue(label: "Autenticator.(UUID().uuidString)")
//MARK:- Functions
func refreshToken<S: Subject>(using subject: S) where S.Output == Bool {
queue.sync {
URLSession.shared
.dataTaskPublisher(for: APIRouter.refreshToken.request()!)
.retry(3)
.sink { com in
print(com)
subject.send(true)
} receiveValue: { data in
print(#line, data)
do {
let jsonDecoder2 = JSONDecoder()
let user = try jsonDecoder2.decode(User.self, from: data.data)
LocalData.loggedInUser = user
LocalData.token = user.token
} catch {
print(#line, error)
}
}
.store(in: &disposables)
}
}
func tokenSubject() -> CurrentValueSubject<Bool, Never> {
return CurrentValueSubject(true)
}
}
Any input would be greatly appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…