What is Scope in Dagger and how to create a custom Scope?
sobes.tech AI
Answer from AI
Scope in Dagger defines the lifetime of objects within the dependency graph. Objects marked with the same Scope will be created once within that Scope and reused throughout its existence.
Examples of built-in Scopes: @Singleton, @ActivityScope (often used in examples, but not part of the standard Dagger library).
To create a custom Scope, declare an annotation with the meta-annotation @Scope:
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomScope {
}
Then, this Scope is applied to components and modules/providers whose objects should have this lifetime:
@MyCustomScope
@Component(modules = MyModule.class)
public interface MyComponent {
// Methods to obtain dependencies
}
@Module
public class MyModule {
@Provides
@MyCustomScope
MyObject provideMyObject() {
// Logic to create the object
return new MyObject();
}
}
A component with a custom Scope creates singletons within its own lifetime. As long as an instance of this component exists, objects marked with its Scope will be reused. When the component is destroyed and a new one is created, new instances of the scoped objects will be created again.