Java – Android architecture blueprint “todo MVP dagger”, where is @ provides for tasksrepository?
View the Android architecture blueprint "todo MVP dagger" here: https://github.com/googlesamples/android-architecture.
I'm trying to understand the implementation of dagger2, and I can't seem to figure out how they let dagger2 provide tasks repository
They have @ provides for "providetaskslocaldatasource" and "providetasksremotedatasource", but which is the actual taskrepository?
In the todoapplication class, they have:
@Inject TasksRepository tasksRepository;
How can I inject it without @ provides?
If I try to use the same method in my own application, I will receive this error:
So I looked everywhere in blueprints code, but I couldn't see how they did it Are there any tips that allow them not to have @ provides? It will certainly build up, so they bypass it in some way
Someone asked the same question on the actual GitHub page, but there was no answer at the time of writing this article https://github.com/googlesamples/android-architecture/issues/561.
My latest submission at the time of writing is "082bd72d62472f9caadd2979046067fb928bbfef"
Solution
In the repository you mentioned, dagger 2 knows how to inject tasksrepository.xml by using the constructor of the @ inject tag From source:
@Inject TasksRepository(@Remote TasksDataSource tasksRemoteDataSource,@Local TasksDataSource tasksLocalDataSource) { mTasksRemoteDataSource = tasksRemoteDataSource; mTasksLocalDataSource = tasksLocalDataSource; }
Since the constructor is annotated with @ inject, dagger 2 will try to inject tasksrepository into consumers (such as todoapplication) using the constructor
Since tasksdatasource is bound in tasksrepositorymodule, dagger 2 has enough information to perform injection without additional @ provides or @ bindings methods
Similarly, you can do the following:
class Foo { private final Bar bar; @Inject Foo(Bar bar) { this.bar = bar; } } class Bar { @Inject Bar() {} } class Activity extends AppCompatActivity { @Inject Foo foo; }
Dagger 2 will be able to inject foo into appcompatactivity Why?
>Dagger 2 knows how to construct a bar object (by calling an empty constructor) > dagger 2 knows that when creating a foo instance, you must use a constructor with @ inject annotation and a single parameter bar. > Foo has no other dependencies, in other words, a complete object graph is available