Junior — Middle
In what situations is it recommended to use the Provides module in Dagger for dependency provision?
sobes.tech AI
Answer from AI
The @Provides annotation in Dagger is used within modules to define methods that create and supply dependencies. It is recommended to use @Provides in the following situations:
- When creating a dependency requires complex logic or configuration that cannot be expressed through a constructor with
@Inject. - If you need to provide an interface or abstraction, and the implementation is created inside the method.
- For creating objects that cannot be annotated with
@Inject(e.g., classes from third-party libraries). - When you need to control the lifecycle or parameters of the created object.
Example:
@Module
public class NetworkModule {
@Provides
OkHttpClient provideOkHttpClient() {
return new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.build();
}
@Provides
Retrofit provideRetrofit(OkHttpClient client) {
return new Retrofit.Builder()
.baseUrl("https://api.example.com")
.client(client)
.build();
}
}
Here, @Provides methods create and configure objects that cannot simply be annotated with @Inject."}]}]}```json{