There are 2 scopes in my application, which are 1) Singleton
lives along with the application process and 2) UserScope
starts immediately after the user log in and ends immediately before the user log out.
When user is not logged-in, there's a general OkHttpClient
(from OkHttp3) for use which has no authentication, while during the UserScope
all network must go through an authenticated OkHttpClient
.
There are two solutions come to my mind by neither I think is best practice:
1): Using a Singleton
OkHttpClient with a TokenInterceptor, which has a setToken
method, use it everywhere and set different token values. This is currently what I'm using. The main problem here is that the setToken
method and the getter must be synchronized to ensure thread safety.
2): Using @Named
injection. This is worse. Say we name two types of OkHttpClient, unauthorized
and authorized
, the problem is that the authorized
object is not always there as the user maybe not logged-in.
So what's the best practice to work with this use case?
Background: In my project there's Dagger2, Retrofit2 and OkHttp3. And the server will send different sets of data when authorized and unauthorized.