I'm writing an interceptor such that when I get 401 I'm using the refresh tokens to get a new access token in the background and then add that token to the request.
Code example:
@Override
public Response intercept(final Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (response.code() != 200) {
try {
new TokenRequestTask(tokenRequest, request, OkHttpresponse, chain).execute().get(5000, TimeUnit.MILLISECONDS);
response = chain.proceed(request);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
return response;
}
In the async task In postExecution, I'm changing the header of the request by adding received fresh auth token. But the problem is that the output is not as per intended. The function is returning the old response as the result of the async task comes after that. Ideally, it should wait for async task result and then return but is not happening. How to achieve this?