Junior — Middle
Can you explain what a module in Dagger is and how it is used to provide dependencies?
sobes.tech AI
Answer from AI
In Dagger, @Module is a class that contains methods annotated with @Provides. These methods describe how to create and supply dependencies that Dagger can then inject into other parts of the application.
A module helps centralize the logic for creating objects, especially if their creation is complex or requires parameters. For example, if you need to create an object with specific settings or obtain an instance from a third-party library.
Example of a module:
@Module
public class NetworkModule {
@Provides
OkHttpClient provideOkHttpClient() {
return new OkHttpClient.Builder().build();
}
@Provides
Retrofit provideRetrofit(OkHttpClient client) {
return new Retrofit.Builder()
.client(client)
.baseUrl("https://api.example.com")
.build();
}
}
Then this module is connected to a Dagger component responsible for dependency injection.