Sobes.tech
Junior — Middle

How is the lifetime of a Subcomponent managed in Dagger?

sobes.tech AI

Answer from AI

In Dagger, the lifetime of a Subcomponent is managed through a scope, which is linked to the lifecycle of the component that creates this Subcomponent.

Key points:

  • A Subcomponent is created from a parent component and inherits its dependencies.
  • The lifetime of the Subcomponent is limited to the lifetime of the parent component but can be shorter.
  • The @Scope annotation is used to manage the lifetime, defining the scope.
  • When the parent component is destroyed, all its Subcomponents also become unavailable.

Example:

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

@ActivityScope
@Subcomponent
public interface MySubcomponent {
    void inject(MyActivity activity);
}

@Singleton
@Component
public interface AppComponent {
    MySubcomponent.Factory mySubcomponentFactory();
}

Here, the Subcomponent with the ActivityScope lives within the lifecycle of the Activity, while the AppComponent is longer-lived. The management of the lifetime occurs through creating and destroying the Subcomponent at the appropriate moment.