Trikke
Trikke

Reputation: 268

How to provide a singleton in a dagger module with 2 different implementations

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

Answers (1)

Jake Wharton
Jake Wharton

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

Related Questions