Having the SharedPreferences provided from one dagger2 module, in another dagger2 module would like to use it,
how to do it?
the code below seems not working.
/** the component */
@Singleton
@Component(modules = arrayOf(DataManagerModule::class,
AnotherModule::class))
interface DataManagerComponent {
fun getDataManager() : DataManager
fun getSharedPreferences() : SharedPreferences
}
/** the module 1 */
@Module
class DataManagerModule(@ApplicationContext private val appContext: Context) {
@Singleton
@Provides
@ApplicationContext
fun provideApplicationContext(): Context = appContext
@Singleton
@Provides
fun provideSharedPreferences(): SharedPreferences {
return appContext.getSharedPreferences(appContext.packageName,
Context.MODE_PRIVATE)
}
}
/** the module 2 */
@Module
class AnotherModule(private val config1: String?, private val config2: Int?) {
@Provides
@Singleton
internal fun provideClass2(context: Context): Class2 {
if (config2 == null) {
// how to get the preferences???
// getSharedPreferences().edit().getInt(Constants.Settings, -1)
}
return class2(config1, config2, context)
}
}
Since you have already defined how to retrieve SharedPreferences from DataManagerModule class you can simply change
to
Have another class extend the Application class and declare it to the AndroidManifest like so:
Modify your component to include an inject function
Then inject it to the activity
since all these artifacts share the same scope, and the component is built using both modules, you should be able to simply add
SharedPreferences
as a parameter toprovideClass2()
in order to use it in the construction ofClass2
, like so: