How to sync / limit some async HTTP calls in android

I am using Android Async Http Library in my application to make asynchronous HTTP requests.

I came to a situation in my android app where the following happens. My web api uses access token and refresh token. On every request I make, I check if the access token is valid. If it's not me, then I issue an http message to navigate to the new access token using the refresh token.

Now I noticed the following situation.

the user of my app leaves their phone inactive long enough for the access token to expire. When they wake up the phone. In my function, onResume()

I am running two separate HTTP requests.

  • Request 1 checks the access token and determines if it is invalid. Then it issues a request refreshAccessToken

    .
  • While Request 1 is waiting for a response, Request 2 also checks the access token and determines if it is invalid. And it issues a request as well refreshAccessToken

    .
  • Request 1 returns successfully and refreshes access tokens and refreshes token values.
  • Request 2 then gets a response 401

    from the api as the refresh token it provided is already in use. My application then thinks there is an error with refreshToken and logs in the user.

This is clearly not true and I would like to avoid it. I have average time doing double check in method refreshAccessToken

onFailed()

. To check if the accessToken is valid. However, this is inefficient as I am still collecting two claims over the air and my API has to handle the failed update attempt.

Question: Now my problem is that I cannot use any locks or sync as you cannot block the main UI thread in android. And Android Async Http Library handles all the different streams, etc.

+3


source to share


1 answer


Request 2 also checks the access token and determines its not valid.

It is not right. Since request 1 may already issue a request refreshAccessToken

, then the state of the access token cannot be determined by contacting the server.



So getAccessToken()

what you need is a combined operation that validates the access token, issues refreshAccessToken

when needed, and when called in parallel, only waits for the previously called operation getAccessToken()

.

UPDATE. refreshAccessToken

is part of a class that serves as a gatekeeper and only allows requests to run if the access token is updated. If the token is not renewed, the gatekeeper sends one request to renew the token. In the meantime, input requests are stored in a queue. When the token is refreshed, the gatekeeper allows the requested requests to be saved.

+2


source







All Articles