Reputation: 702
I'm pretty new to RxSwift and, I am using Moya with RxSwift for networking in my app. I have the following function which is used for every request, for a given ProviderType.
open func request(for target: ProviderType) -> Observable<Response> {
return provider.rx.request(target)
.filterSuccessfulStatusCodes()
.asObservable()
.catchError { [weak self] error in
guard let self = self else {
return Observable.error(error)
}
return Observable.error(self.handleError(with: error))
}
}
This works pretty well, but now I want to retry the request when the request fails with a status code of 401, after fetching the refresh token. I found this comment on a GitHub issue which tells how it can be achieved but I am still confused how it will work in my case (the comment does not provide context related to how the refresh token mechanism works).
Upvotes: 0
Views: 2350
Reputation: 33979
I wrote an article about how to handle retrying when encountering an invalid token. The article goes into more depth but the TLDR is that you need to use the retryWhen
operator instead of catchError
.
By using retryWhen
you can listen for the appropriate error, and attempt to refresh the token when the 401 comes in. If you get a new token, then it's just a matter of emitting a value from the closure's Observable. If refreshing the token fails, then simply emit an error with the reason why.
Also, at the beginning of the stream, you need some way of inserting the refreshed token.
Upvotes: 1