androidretrofitnetworkonmainthread

Retrofit Request Interceptor blocks the main thread


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.


Solution

  • 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);
      }
    }