Sobes.tech
Junior — Middle

How is Dagger configured and integrated into the project?

sobes.tech AI

Answer from AI

To set up and implement Dagger in an Android project, the typical steps are:

  1. Add dependencies: Include Dagger dependencies (dagger, dagger-compiler) in your build.gradle.
  2. Create components: Define an interface with @Component annotation that connects modules and injection points.
  3. Create modules: Classes with @Module annotation provide methods with @Provides to specify how to create dependencies.
  4. Inject dependencies: Use @Inject annotation in target classes (Activities, Fragments, ViewModels) for fields or constructors.
  5. Initialize component: Usually, create an instance of the component (e.g., in Application class) and perform injection.

Example:

// Module
@Module
class NetworkModule {
    @Provides
    Retrofit provideRetrofit() {
        return new Retrofit.Builder()
            .baseUrl("https://api.example.com")
            .build();
    }
}

// Component
@Component(modules = {NetworkModule.class})
interface AppComponent {
    void inject(MainActivity activity);
}

// In Activity
public class MainActivity extends AppCompatActivity {
    @Inject
    Retrofit retrofit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((MyApplication) getApplication()).getAppComponent().inject(this);
        // Now retrofit is available for use
    }
}

Thus, Dagger allows centralized dependency management, simplifying testing and maintenance of code.

How is Dagger configured and integrated into the… - sobes.tech