Why using different scopes with Android Hilt if all can work with SingletonComponent

To add a Hilt module you need to do this:

@Module
@InstallIn(SingletonComponent::class)
abstract class MyModule{
...
}

There are different scopes such as ActivityComponent, ViewModelComponent, etc, but it's not clear to me when would I need to use one different from SingletonComponent, after all this covers everything and always work. Is it just a matter of following good practices as with encapsulation?

Upvotes: 6

Views: 1310

Answers (2)

Thracian
Thracian

Reputation: 66759

It's because of lifecycle or scope of your injected objects. If you set your module's scope Fragment for instance, every time you open that Fragment new instance of that object will be created and will be eligible to be garbage collected when your fragment is destroyed. You won't have objects in memory that are not needed anymore and sometimes you might need new instance of your objects with their parameters reset instead of having Singleton objects.

Upvotes: 4

Nikola Despotoski
Nikola Despotoski

Reputation: 50538

It boils down to the use cases of your dependencies. Scopes are a way to bound the lifespan of an object in your graph. Some use cases require your object live while their container (component) lives. That being said, capping object life is also beneficial memory-wise, why would you keep an object in ApplicationComponent that will live through out application lifecycle, but you only need it in late stage of your app, let's say a Fragment that is shown later down the line.

Some use cases require you having fresh instance of a object each time a particular screen is shown in order to have correct state.

Upvotes: 2

Related Questions