'How to repeat Volley requests after authentication failure and token refresh

I am getting data from an API using Volley and JsonObjectRequest. I have many different calls to different endpoints, and I have a separate class which handles any network/authentication errors. Since my authentication token needs to be refreshed every hour, there are moments when one of my API calls returns with authentication failure - the token is expired. Then I make a request to the API to refresh the token. But once I get the new token back, I need to rerun the API network call which previously failed.

Ideally I would pass along the 'request' object of type JsonObjectRequest to my method which refreshes the token, so that it can add it back to the RequestQueue once we get the new token back. For example:

val request = object : JsonObjectRequest(
        Method.GET,
        url,
        null,
        Response.Listener { response ->
            //call was successful
        },
        Response.ErrorListener { e ->
            //token expired, so make a call to refresh token and then repeat this same reqeuest
            handleNetworkError(e, **request**)
        }) {
        override fun getHeaders(): MutableMap<String, String> {              
            val headers = HashMap<String, String>()
            headers["Authorization"] = "$accesstoken"
            return headers
        }
    }
    mRequestQueue.add(request)

But I can't access the 'request' object from within the ErrorListener. I want to have only one method to refresh the token, so that if any one of the other API calls fails due to authentication, I call the refreshToken() method and when it completes it will repeat whichever API call failed earlier.

Any good and clean way of doing this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source