I'm trying to understand the use of the @Reusable
scope of Dagger. From the documentations what I can understand is that if a provider is scoped with @Singleton
or any other custom scope, then the object will be created first and then cached for the entire lifetime of the component. So, for objects which don't always need to be the same instance or which are less often used, this approach will end up in wasting memory.
But if we go for a non-scoped provider, each time it will create a new instance, and since object instantiation is expensive especially in environments such as Android, where allocations can be expensive, this may cause performance issues.
@Reusable
scope lies somewhere between No-scope and Scoped instances.
From the documentation
Sometimes you want to limit the number of times an @Inject-constructed class is instantiated or a @Provides method is called, but you don’t need to guarantee that the exact same instance is used during the lifetime of any particular component or subcomponent
How does it work exactly? Suppose I have a reusable provider in my AppComponent
, won't it always give me the same instance?
If I inject the same dependency in any Subcomponent
, will I be getting the same instance? When exactly will the cached object be freed up for GC?
I tried with a sample, creating a @Reusable
object in my AppComponent
module and injecting the same from my subcomponents.
What I can see is that it is behaving exactly as @Singleton
.
What performance improvement can we achieve from @Reusable
?
Which are the possible usecases where we should prefer @Reusable
?
Is it a good idea to scope all the state-less objects (where it doesn't matter whether we get the same instances) such as Util classes, Gson, Glide, etc. as @Reusable
?