Interview frequency: …
Short answer
Scopes tie dependency objects to the lifecycle of specific Android components: @Singleton for the whole app, @ActivityScoped for the activity, and @ViewModelScoped for the ViewModel's lifecycle.
Explanation
If you do not specify a scope (unscoped), Hilt creates a new instance of the object every time it is requested. Specifying @Singleton guarantees only one instance exists in the whole app inside the SingletonComponent. Specifying @ActivityScoped guarantees the same instance is shared for as long as the Activity lives, while @ViewModelScoped keeps the instance alive across configuration changes with the ViewModel.
Code example
@Module
@InstallIn(ViewModelComponent::class)
object FeatureModule {
@Provides
@ViewModelScoped
fun provideFeatureState(): FeatureState = FeatureState()
}Common mistakes
- Using @Singleton on everything, which consumes memory with no reason and keeps unnecessary objects alive all the time.
- Trying to inject an object with a narrow scope (such as @ActivityScoped) into an object with a broader scope (such as @Singleton), causing a compile-time error.