7

This issue has already been mentioned here, but it is a quite old question and I couldn't find any other information.

The Request Interceptor of a Retrofit API call is executed on the main thread. This is an issue when dealing with AccountManager to add auth tokens to the request header, like

String token = mAccountManager.blockingGetAuthToken(account, AuthConsts.AUTH_TYPE, false);

Same issue is discussed on G+ and there is a related issue on GitHub here.

While this all gets worked (thanks SquareUp!), what is the best way to work around it? Wrapping the Retrofit calls in an AsyncTask or similar feels like invalidating the whole idea.

Community
  • 1
  • 1
ticofab
  • 7,551
  • 13
  • 49
  • 90
  • 1
    Retrofit's job is *not* to move network calls off the main thread. It is simply to provide an interface to a Rest service. I used [this](https://github.com/paristote/youcast-android/blob/master/src/com/philipoy/youtubedl/rest/YouCastInterface.java) approach in a project recently to add a request interceptor to every call made with Retrofit. – Philippe A Jan 19 '15 at 09:55

2 Answers2

17

Retrofit's interceptor is for modifying the request with known information. That is to say that it should be a simple and instance transformation.

The best approach for what you are looking for is to use OkHttp's interceptors to add the header. These will run on the background thread.

class AuthInterceptor implements Interceptor {
  @Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    String authHeader = // TODO get auth token
    request = request.builder()
      .header("Authorization", authHeader)
      .builder();

    return chain.proceed(request);
  }
}
Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
1

You could simple use peekAuthToken to get the token and only if the result is null would you need to "refresh" the token you could then either let the request fail or asynchronously get the new token

forcewill
  • 1,637
  • 2
  • 16
  • 31