Sobes.tech
Junior — Middle

How is the Hof dependency, marked with the Singleton annotation, preserved within the Dagger dependency injection framework?

sobes.tech AI

Answer from AI

In Dagger, the @Singleton annotation guarantees that the object will be created only once within the scope of a component and will be reused for all subsequent dependency requests.

How it works:

  • When a Dagger component is created, it stores singleton instances in its internal cache.
  • On the first dependency request with the @Singleton annotation, Dagger creates the object and saves it.
  • On subsequent requests of the same type, Dagger returns the stored instance instead of creating a new one.

It is important to note that the singleton scope is limited to the component. If there are multiple components, each can have its own singleton instance.

Example:

@Singleton
@Component
interface AppComponent {
    MyService getMyService();
}

@Singleton
class MyService {
    @Inject
    MyService() {}
}

Here, MyService will be created once at the AppComponent level and reused.

How is the Hof dependency, marked with the Singleton… - sobes.tech