JakeWharton/u2020

Update request header when access token updates Dagger and Retrofit

Sinyuk7 opened this issue · 1 comments

Thank you for giving me such a good example to learn something...but now I have some trouble in using Dagger and Retrofit.And I want to update access token in network request...

😢Sorry,my English is not good , so give you an example may be much clear.Starting from scratch, my idea is like this:

provide an access token saved in shared preference

@Provides
@ForOauth
Preference<String> provideAccessToken(RxSharedPreferences prefs) {
    return prefs.getString(PrefsUtils.KEY_ACCESS_TOKEN);
}

use access token to create an interceptor and added into okhttp client

@Provides
@Singleton
@Named("Cached")
public OkHttpClient provideOkHttpClientWithCache(Application application, @ForOauth OauthInterceptor oauthInterceptor) {
      ...
    builder.addInterceptor(oauthInterceptor);
      ...
}

and I provide the OauthInterceptor instance by its constructor

@Inject
public OauthInterceptor(@ForOauth Preference<String> accessToken) {
    this.accessToken = accessToken;
    Timber.tag("OauthInterceptor");
}

But cause the okhttp client is a singleton,it won't change when the access token in prefs updates.An alternative way I thought that may work is to use a custom scope like @ForOauth or something, but it's just a rough sketch...

By the way, I have another idea like this:

get the access token from prefs in the intercept() method , so every time I can have a request header which contains the latest access token.

@Override
public Response intercept(Chain chain) throws IOException {
    Request.Builder builder = chain.request().newBuilder();
    if (accessToken.isSet()) {
        // Preference<String> accessToken
        builder.header("Authorization", ACCESS_TYPE + accessToken.get());
    } else {
        builder.header("Authorization", "Bearer xxxxxx");
    }
    return chain.proceed(builder.build());
}

But I haven't really experimented with this idea,and I think it's not right 😂

I wonder whether I have to create a new okhttp client instance every time or I can just update the access token then the okhttp client singleton can refresh its interceptor...

So could you please give me some advice , or a simple working example.

Thanks in advance 😊

StackOverflow is the right place for this. Not here (or Dagger's issue tracker), but you already posted there: http://stackoverflow.com/questions/39136081/update-request-header-when-access-token-updates-dagger-and-retrofit