Sobes.tech
Junior — Middle

How to define the scope of dependencies in Dagger and why is it needed?

sobes.tech AI

Answer from AI

In Dagger, scope defines the lifecycle and uniqueness of dependencies. It is used to manage the lifespan of objects and avoid unnecessary creation of new instances.

For example, if a component and a dependency provider are marked with the same scope, Dagger will create a single instance of that dependency for the entire lifespan of the component.

Scope helps to:

  • Reuse objects within the same scope (e.g., session or screen).
  • Control the creation and destruction of dependencies.
  • Avoid memory leaks and excessive resource consumption.

An example of defining a scope:

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScope {}

@ActivityScope
@Component(modules = MyModule.class)
public interface MyComponent {
    // dependencies
}

Here, ActivityScope ensures that all dependencies with this annotation are created once per the component's lifecycle.