I'm trying to wrap my head around the use of Dagger 2 in my project with Retrofit, RxJava, MVP implementation. However, I'm starting small by reading guides and watching videos and just when I thought I understood how it works, it appears I don't. Here is the sample I'm trying to understand.
Module:
@Module
public class AppModule {
private App app;
public AppModule(App app) {
this.app = app;
}
@Provides @Singleton public SharedPreferences provideSharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(app);
}
@Provides @Singleton public HelloModel provideHelloModel(SchedulerProvider schedulerProvider,
HelloDiskCache helloDiskCache, HelloService helloService, Clock clock) {
return new HelloModel(schedulerProvider, helloDiskCache, helloService, clock);
}
@Provides public HelloDiskCache provideHelloDiskCache(SharedPreferences prefs) {
return new HelloDiskCache(prefs);
}
@Provides public HelloService provideHelloService() {
return new HelloService();
}
@Provides public SchedulerProvider provideSchedulerProvider() {
return SchedulerProvider.DEFAULT;
}
@Provides public Clock provideClock() {
return Clock.REAL;
}
@Provides @Nullable public LayoutInflaterFactory provideLayoutInflaterFactory() {
return null;
}
Component
@Component(
modules = AppModule.class
)
@Singleton
public interface AppComponent {
HelloModel getHelloModel();
HelloDiskCache getHelloDiskCache();
MainActivity inject(MainActivity activity);
HelloFragment inject(HelloFragment fragment);
}
In the fragment, presenter is injected (where is this coming from?)
@Inject HelloPresenter presenter;
And in the presenter, there is a constructor injection
@Inject HelloPresenter(HelloModel helloModel) {
this.model = helloModel;
}
So, how come we can inject a presenter in the fragment, and why can we inject in the presenter? The answer does not have to be very elaborate I just feel stupid because I can't trace where it is coming from.
@Inject
-annotated constructor is an alternative to a @Provides
-annotated method for a dependency when there's not much configuration to do.
Since HelloPresenter
has such constructor, Dagger discovers it automatically and is able to inject this dependency or use it to construct and provide other objects in the graph.
A class with an @Inject
-annotated constructor can itself be annotated with a scope annotation (e.g., @Singleton
). In this case, only components with the matching scope will be able to see it.
In general, this type of providing dependencies is less verbose, but not always you can use it (e.g., Activity
, SharedPreferences
). In such cases you have to go with a @Module
and a @Provides
method.