I'm reading this great tutorial that explains how @Component.Builder
works in Dagger 2. The author did a good job and the article is straight forward, but there still are some confusing I need to clarify: the default implementation of Dagger 2 looks something like this:
The component:
@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
SharedPreferences getSharedPrefs();
}
The module:
@Module
public class AppModule {
Application application;
public AppModule(Application application) {
this.application = application;
}
@Provides
Application providesApplication() {
return application;
}
@Provides
@Singleton
public SharedPreferences providePreferences() {
return application.getSharedPreferences(DATA_STORE,
Context.MODE_PRIVATE);
}
}
Component instantiating:
DaggerAppComponent appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this)) //this : application
.build();
According to the article, we can simplify this code even more by avoiding passing arguments to the module constructor using @Component.Builder
and @BindsInstance
annotations, then the code will look like this:
The component:
@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
SharedPreferences getSharedPrefs();
@Component.Builder
interface Builder {
AppComponent build();
@BindsInstance Builder application(Application application);
}
}
The module:
@Module
public class AppModule {
@Provides
@Singleton
public SharedPreferences providePreferences(
Application application) {
return application.getSharedPreferences(
"store", Context.MODE_PRIVATE);
}
}
And the component instantiating:
DaggerAppComponent appComponent = DaggerAppComponent.builder()
.application(this)
.build();
I almost understand how the above code works, but here is the part I don't understand: how did we get from appModule(new AppModule(this))
to application(this)
when we are instantiating the component?
I hope the question was clear and thanks.