Sobes.tech
Junior — Middle

Can you explain the purpose of the @Singleton annotation in Dagger and how it affects the lifecycle of objects?

sobes.tech AI

Answer from AI

The @Singleton annotation in Dagger is used to indicate that a component or provider should create and supply a single instance of an object throughout the lifecycle of the component (e.g., the application).

This means that when using @Singleton, Dagger guarantees that:

  • The object is created once upon the first request.
  • All subsequent requests receive the same instance.

Thus, @Singleton affects the lifecycle of objects, ensuring a singleton pattern within the Dagger component.

Example of usage:

@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
    MyRepository getMyRepository();
}

@Module
public class AppModule {
    @Provides
    @Singleton
    MyRepository provideMyRepository() {
        return new MyRepository();
    }
}

In this example, MyRepository will be created once and reused wherever it is injected via AppComponent.

It is important to remember that the scope of @Singleton depends on the scope of the component: if the component lives long (for example, the entire application lifecycle), then the singleton will live long as well.

Can you explain the purpose of the @Singleton… - sobes.tech