Dagger Hilt: Scope dependencies for parent-/child-fragments

Viewed 824

I am trying to find a solution in how to define Hilt in a certain fragment related scenario. I have the following setup:

  • Activity
    • Parent Fragment 1
      • Child Fragment 1
      • Child Fragment 2
      • ...
      • Child Fragment n-1
    • Parent Fragment 2
      • Child Fragment 1
      • Child Fragment 2
      • ...
      • Child Fragment n-1

Parent Fragment 1 is using the dependency A. The instance of that dependency is something I want to share only between that parent fragment and all of its child fragments. The parent fragment 2 + its child fragments should use a different instance than the parent fragment 1 + children. Generally his structure should have only two instances of any given dependency - one for the first flow and one for the second.

I can see that a custom scope might work here but I am uncertain about how to use that in regards to Hilt.

1 Answers

You can do this using dagger-hilt by adding @AndroidEntryPoint in each parent Fragment and their child's view. Then your Parent Fragment 1 and Parent Fragment 2 will have different fragment scope with different instances as per the dagger-hilt explanation. See below note from dagger-hilt:

A common misconception is that all fragment instances will share the same instance of a binding scoped with @FragmentScoped. However, this is not true. Each fragment instance gets a new instance of the fragment component, and thus a new instance of all its scoped bindings.

Also, see below dagger graph and the scopes hierarchy:

enter image description here

More details in their documentation.

Also, Don't use custom scopes until it's really necessary since it has performance and overhead issues.

Related