I have two questions about Dagger2
and it's Singleton
scope,
I used Retrofit
and GSON
but it's just for the example, I want to make sure I understand Dagger2
correctly.
I have NetowrkModule
like:
@Module
public class NetworkModule {
@Provides
@Singleton
Retrofit provideRetrofit(OkHttpClient okHttpClient, GsonConverterFactory gsonConverterFactory) {
return new Retrofit.Builder()
.addConverterFactory(gsonConverterFactory)
.baseUrl("https://example.com")
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
@Singleton
@Provides
OkHttpClient provideOkHttpClient() {
return new OkHttpClient.Builder().build();
}
@Singleton
@Provides
GsonConverterFactory provideGson() {
return GsonConverterFactory.create();
}
}
and ApplicationComponent
:
@Singleton
@Component(modules = {
AndroidSupportInjectionModule.class,
ApplicationModule.class,
ViewBuildersModule.class,
AuthServiceModule.class
})
public interface ApplicationComponent {
@Component.Builder
interface Builder {
@BindsInstance
Builder application(MyApplication application);
ApplicationComponent build();
}
void inject(MyApplication app);
}
- Should I annotate
OkHttpClient
provider as singleton too? (I needRetrofit
instance to be singleton in application scope). What is the difference between provide
GsonConverterFactory
VS createGsonConverterFactory
in retrofit provider like:@Module public class NetworkModule { @Provides @Singleton Retrofit provideRetrofit(OkHttpClient okHttpClient, GsonConverterFactory gsonConverterFactory) { return new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl("https://example.com") .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } @Singleton @Provides OkHttpClient provideOkHttpClient() { return new OkHttpClient.Builder().build(); } }