@bindsInstance is used to remove the constructor from the modules and module chains where you get the component.
Without @BindsInstance
@Module
public class AppModule {
private final Application application;
public AppModule(Application application) {
this.application = application;
}
@Provides
@Singleton
Application provideApplication() {
return application;
}
@Provides
@Singleton
public SharedPreferences providePreferences() {
return application.getSharedPreferences("store",
Context.MODE_PRIVATE);
}
}
These modules (ToastMakerModule and SensorControllerModule) are intended for training purposes, they get context and are created, and in real examples they can be impractical
public class ToastMaker {
private Application application;
public ToastMaker(Application application) {
this.application = application;
}
public void showToast(String message) {
Toast.makeText(application, message, Toast.LENGTH_SHORT).show();
}
}
@Module
public class ToastMakerModule {
@Singleton
@Provides
ToastMaker provideToastMaker(Application application) {
return new ToastMaker(application);
}
}
@Singleton
@Component(modules = {AppModule.class, ToastMakerModule.class, SensorControllerModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
@Component.Builder
interface Builder {
AppComponent build();
Builder appModule(AppModule appModule);
Builder sensorControllerModule(SensorControllerModule sensorControllerModule);
Builder toastMakerModule(ToastMakerModule toastMakerModule);
}
}
Create such a component
appComponent = DaggerAppComponent
.builder()
.appModule(new AppModule(this))
.sensorControllerModule(new SensorControllerModule())
.toastMakerModule(new ToastMakerModule())
.build();
WITH @BindsInstance
@Module
public class AppModule {
@Provides
@Singleton
public SharedPreferences providePreferences(Application application) {
return application.getSharedPreferences("data",
Context.MODE_PRIVATE);
}
}
component
@Singleton
@Component(modules = {AppModule.class, ToastMakerModule.class, SensorControllerModule.class})
public interface AppComponent {
void inject(MainActivity mainActivity);
@Component.Builder
interface Builder {
AppComponent build();
@BindsInstance
Builder application(Application application);
}
}
and create such a component
appComponent = DaggerAppComponent
.builder()
.application(this)
.build();
source
share