Junior — Middle
What is the main function of the Singleton annotation and where is it used?
sobes.tech AI
Answer from AI
The @Singleton annotation in Android (for example, when using Dagger for dependency injection) indicates that a class should have a single instance within a specific component or the entire application.
The main function is to ensure that multiple requests for the dependency return the same object. This is useful for managing state, conserving resources, and ensuring data consistency.
Example of usage with Dagger:
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
MyRepository getRepository();
}
@Singleton
public class MyRepository {
// ...
}
Here, MyRepository will be created once and reused wherever needed.