0

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.

Marvin
  • 1,726
  • 1
  • 17
  • 25
  • The way I see it there's no issue with option 1. You have one dependency - the ``OkHttpClient`` and its interceptors change behaviour depending on the user session. Having a synchronised setter and getter is not an issue. The lack of synchronisation was a problem solved long time ago and nowadays shouldn't be seen as such. Synchronisation is actually a solution and a pretty good one :) – Fred Feb 28 '17 at 10:24

1 Answers1

1

I use UserScope for OkHttpClient instance, so I have single OkHttpClient while user is logged in. This OkHttpClient is instantiated once after user login, and I set token exactly once. If user isn't logged I use another OkHttpClient with scope, related to my LoginActivity lifecycle.