具有多个异步 API 调用的 Okhttp 身份验证器

Okhttp Authenticator with multiple asynchronous API calls

我面临 API 实施了令牌刷新系统。我正在为 API 请求使用 Retrofit 并且我设置了 Authenticator 来检测何时给出 Error 401 并发出新请求以刷新令牌。

问题在于,如果应用同时有多个请求(例如,在 ViewPager 中填充多个页面,或者在 Service 中的 API 请求中填充多个页面当用户正在使用应用程序并引发另一个 API 请求时),API 多次响应 401,因此,应用程序多次请求 Authenticator

你是如何解决这个问题的? 我正在考虑使用 Singletonboolean 来检测应用程序是否正在执行令牌刷新调用,但在我看来这并不是实现它的最佳方法。

我会说 Singleton 是个好主意,但是 Singleton 我的意思是在 api 客户端对象中有一个凭据对象 - 它在对象范围内是单例而不是整体适用范围。你建议做类似于 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.