I am facing an API with a token refresh system implemented. I am using Retrofit
for the API requests and I have set an Authenticator
to detect when an Error 401
is given and make new request to refresh the token.
The problem is that if the app has multiple requests at the same time (for instance, to fill multiple pages in a ViewPager
or in an API request in a Service
while user is using the app and cause another API request), the API is responding with 401 multiple times and, because of that, the application is requesting the Authenticator
multiple times.
How do you manage to fix that?
I'm thinking about a Singleton
with a boolean
to detect if the application is doing a token refresh call but it doesn't seems to me the best way to achieve it.
I would say Singleton
is a good idea, but by Singleton
I mean having a credentials object inside api client object - it would be singleton in object scope instead of whole application scope. You'd recommend doing something similar to this answer
I would introduce new object to be used as a semafore - it would be blocked every time when 'credentials are being refreshed'. To make sure that you'll make only one 'refresh credentials' call, you need to call it in block of code which is synchronized with object.