Add Retrofit Requestinterceptor with dagger at runtime

I am using dagger and modification. I attach my dagger retrofit service.

Now I want to make an authorization request to get the accessToken.

Then I want to improve my api module with a request interceptor to use this access token for future requests.

My idea is to use the ObjectGraph.plus () method after I got the access token, but I'm not sure if this is the best way to do it.

Can anyone point me in the right direction or maybe there is an example project on github?

+3


source to share


1 answer


The key is to always add RequestInterceptor

and then change if it adds a header.

class ApiHeaders implements RequestInterceptor {
  private String authValue;

  public void clearAuthValue() {
    authValue = null;
  }

  public void setAuthValue(String authValue) {
    this.authValue = authValue;
  }

  @Override public void intercept(RequestFacade request) {
    String authValue = this.authValue;
    if (authValue != null) {
      request.addHeader("Authorization", authValue);
    }
  }
}

      



This way you can insert your singleton ApiHeaders

when you need to set or clear a token.

+10


source







All Articles