I am new to Dagger and Retrofit. I am having issue where multiple instances of retrofit custom interceptor are being generated despite declared singleton in dagger module. I onl
You should not call provideRequestInterceptor
directly
@Provides @Singleton
public Retrofit provideRetrofitInstance(AuthenticationRequestInterceptor authInterceptor)
{
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add session headers interceptor
httpClient.addInterceptor(authInterceptor);
// add logging as last interceptor
httpClient.addInterceptor(logging);
return new Retrofit.Builder()
.baseUrl(getConfig().getBaseUrl())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient.build()) //for logging purpose remove later
.build();
}
There is on point creating another of instance OkHttpClient.Builder within the provideRetrofitInstance method, you have already provided it in your ApiModule. Be nice and use as httpClient argument instead.
@Module
public class ApiModule
{
private Config config;
public ApiModule(Config config) {
this.config = config;
}
@Provides @Singleton
public OkHttpClient.Builder provideOkHttpClient()
{
return new OkHttpClient.Builder();
}
@Provides @Singleton
public AuthenticationRequestInterceptor provideRequestInterceptor()
{
return new AuthenticationRequestInterceptor();
}
@Provides @Singleton
public Retrofit provideRetrofitInstance(OkHttpClient.Builder httpClient,
AuthenticationRequestInterceptor authInterceptor)
{
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
//YOU DON'T THIS LINE, REFER TO ARGUMENT LIST
//OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add session headers interceptor
httpClient.addInterceptor(authInterceptor);
// add logging as last interceptor
httpClient.addInterceptor(logging);
return new Retrofit.Builder()
.baseUrl(getConfig().getBaseUrl())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient.build()) //for logging purpose remove later
.build();
}
}