Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 365
ticofab Avatar asked Jan 19 '15 09:01

ticofab


2 Answers

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);
  }
}
like image 87
Jake Wharton Avatar answered Oct 19 '22 08:10

Jake Wharton


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

like image 34
forcewill Avatar answered Oct 19 '22 10:10

forcewill