Reputation: 268
Imagine a dagger module
that has the following two methods to provide an object.
@Provides @Singleton Cache<Settings> providesSettingsCache( Database db )
{
return new StateCache( db, BuildConfig.VERSION_CODE );
}
@Provides @Singleton Cache<User> providesUserCache( Database db )
{
return new StateCache( db, BuildConfig.VERSION_CODE );
}
In my example StateCache
implements both the Cache<User>
and the Cache<Settings>
interface. Now instead of both methods returning an instance of StateCache
, i'd like both methods to obviously point to the same instance.
How can this be achived in Dagger? Does the module
hold a reference the one instance of StateCache
, and have both methods return that?
Upvotes: 2
Views: 1139
Reputation: 76075
Let Dagger manage the StateCache
instance.
@Provides @Singleton StateCache provideStateCache(Database db) {
return new StateCache(db, BuildConfig.VERSION_CODE);
}
@Provides @Singleton Cache<Settings> provideSettingsCache(StateCache cache) {
return cache;
}
@Provides @Singleton Cache<User> provideSettingsCache(StateCache cache) {
return cache;
}
Upvotes: 6