Toni Joe
Toni Joe

Reputation: 8407

How do Dagger 2 scoped components work?

I'm new to Dagger 2 and I managed to grasp the basic of how it works, but I'm confused about how custom scopes really works. So here is the problem: Say I have ActivityScope defined like this:

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

and a scoped component:

@ActivityScope
@Component( modules = ActivityModule.class)
public interface ActivityComponent {
   /* ... */
}

The way I understand it, objects provided by this component will have a single instance that lives as long as the component lives, but what determines how long a component lives? Is it where the component is built (Application, inside an Activity, Fragment ...), or is it something else?

I don't know if this is the right place to ask this question but any help is welcome. Thanks.

Upvotes: 0

Views: 41

Answers (1)

David Medenjak
David Medenjak

Reputation: 34532

The way I understand it, objects provided by this component will have a single instance that lives as long as the component lives [...]

Correct. Scoped objects provided by this component will only exist once. This is not true for unscoped objects, which get recreated every time and can be provided by any component.

[...] but what determines how long a component lives? Is it where the component is built (Application, inside an Activity, Fragment ...), or is it something else?

You do. If you decide to store your component in a static variable—please don't—then that component lives as long as your app is alive and running (and will probably leak the Activity in the process).

If you just keep your component in your Activity it will be garbage collected along with the rest, once the Activity gets destroyed.

Upvotes: 3

Related Questions