3

I'm using dagger and retrofit. I inject my Retrofit services with Dagger.

Now i wanna do a authorization request to get an accessToken.

Afterwards i want to enhance my api module with an Request interceptor to use this access token for future requests.

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

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

AdrianoCelentano
  • 2,461
  • 3
  • 31
  • 42

1 Answers1

11

The key is to always add the RequestInterceptor and then change whether or not it adds the 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 inject your ApiHeaders singleton when you need to set or clear the token.

Jake Wharton
  • 75,598
  • 23
  • 223
  • 230
  • How we can call setAuthValue with authValue at runtime when user Login, if we are using single NetworkModule in the App. – Jagdeep Singh Feb 08 '17 at 09:08
  • @Jake Wharton A similar issue I came across can you please have a look https://stackoverflow.com/questions/45078720/dagger-generating-multiple-instances-of-retrofit-interceptor – user606669 Jul 13 '17 at 11:24
  • @Jake Wharton, we have a similar issue in our company, could you please take a look? https://stackoverflow.com/q/46791074/5727805 Thanks! – MKaro Oct 17 '17 at 13:20