Junior — Middle
Kuidas säilib Daggeri sõltuvuste süstimise raames märgitud Singleton annotatsiooniga Hof'i sõltuvus?
sobes.tech AI
Vastus AI-lt
In Dagger, the @Singleton annotation guarantees that the object will be created only once within the scope of the component (Component) and will be reused for all subsequent dependency requests.
How it works:
- When the 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 stores it.
- On subsequent requests of the same type, Dagger returns the stored instance instead of creating a new one.
It is important that the scope of the singleton 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 will be reused.