You want to supply an object (String name
) as a parameter to your component so that it can be used by other parts. You basically have 2 options to do so.
Module Constructor Parameters
Using module arguments is the "classic" approach that you would use before they introduced the Component.Builder
.
All you do is add what you need to your module constructor, and provide it from the module.
@Module
public class MyModule {
private String name;
MyModule(String name) {
this.name = name;
}
// -----------------------------------------------
// you could obviously just use the field directly
@Provides
Student provideStudent() {
return new Student(name);
}
// ---------------------------------------------------------------------
// alternatively you'd add a Qualifier and add the argument to the graph
@Provides
@Named("name")
String provideName() {
return name;
}
// then you can use it...
@Provides
Student provideStudent(@Named("name") String name) {
return new Student(name);
}
}
The first option that directly uses the name means that it's only available within that module. If you want to make use of constructor injection or use the qualified String you have to add it to the graph as shown second.
With either approach you'd have to manually add the module to the component, since the module does no longer use a default constructor. This is where you'd also supply your argument now.
DaggerMyComponent.builder()
.myModule(new MyModule("some name"))
.build();
Component Builder
The same concept but a different approach would be to use the component builder to achieve the same thing—bind something to the graph.
@Component(modules = MyModule.class)
interface MyComponent {
@Component.Builder
interface Builder {
@BindsInstance Builder name(@Named("name") String name);
MyComponent build();
}
}
@Module
class MyModule {
@Provides
Student provideStudent(@Named("name") String name) {
return new Student(name);
}
}
Here you also just add an object to the graph that can be used. Here, too, you'd have to add it to the component builder
DaggerMyComponent.builder()
.name("some name")
.build();