Sobes.tech
Junior — Middle

How can the lifecycle of a component be managed when using Hilt in Android?

sobes.tech AI

Answer from AI

When using Hilt in Android, the component lifecycle is managed through scopes that tie the lifespan of dependencies to the lifecycle of Android components.

Main scopes in Hilt:

  • @Singleton — the object lives for the entire duration of the application
  • @ActivityScoped — the object lives within a single Activity
  • @FragmentScoped — the object lives within a single Fragment
  • @ViewModelScoped — the object lives within a ViewModel

To manage the lifecycle, classes and dependencies need to be properly annotated, for example:

@AndroidEntryPoint
class MyActivity : AppCompatActivity() {
    @Inject lateinit var repository: MyRepository
}

@ActivityScoped
class MyRepository @Inject constructor() {
    // This dependency will live as long as the Activity
}

Thus, Hilt automatically creates and destroys dependencies according to the component lifecycle, simplifying resource management and preventing memory leaks.