androidkotlindagger-2dagger-hilt

Hilt SingletonComponent vs ActivityComponent scope


I have an app with three activities. Launch Activity A -> Activity B -> Activity -> C

Previous activity is finished while navigating to next activity.

I am injecting objects in Activity A and Activity B in the following way


@Module
@InstallIn(SingletonComponent::class)
class MyProvider {

   // Provides object in Activity A
   @Provides
   fun provideTheObjectA(): SomeObjectA {
       return SomeObjectA()
   }
}


@Module
@InstallIn(ActivityComponent::class)
class AvtivtyBProvider {

  // Provides object in Activity B
  @Provides
  fun provideTheObjectB(): SomeObjectB {
      return SomeObjectB()
  }
}

class ActivtyA: AppCompatActivity(){

  @Inject
  SomeObjectA
}

class ActivtyB: AppCompatActivity(){

  @Inject
  SomeObjectB
}

I want to understand the difference between SingletonComponent and ActivityComponent here.

So,

  1. when activity A is destroyed, will the object A also be destroyed? (Its generated under SingletonComponent scope) (Note: I am not using the @Singleton annotation ) I believe it will be destroyed/garbage collected.
  2. If I had provided the @Singleton annotation, I assume Object A will not be destroyed/garbage collected even though activity A is destroyed.

If so What is the point of @SingletonComponent if I have not used @Singleton annotation?

  1. I assume that when Activity B is destroyed, object B will also be destroyed/garbage collected.

  2. I have not used @ActivtyScoped while created instance of Object B. What difference does it make?

  3. What does having just @Provides annotation without any scope mean ultimately


Solution

  • SingletonComponent and ActivityComponent are definitions of the scope.

    Note: When scoping a binding within an @InstallIn module, the scope on the binding must match the scope of the component. For example, a binding within an @InstallIn(ActivityComponent.class) module can only be scoped with @ActivityScoped.

    In your case SomeObjectB can't be @Singleton, only @ActivityScoped.

    Component lifetimes are generally bounded by the creation and destruction of a corresponding instance of an Android class.