From One Dagger2 Module How To Access The Sharedpreferences Provided In Another Dagger2 Module
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 */
Solution 1:
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 to provideClass2()
in order to use it in the construction of Class2
, like so:
@Provides@Singleton
internal fun provideClass2(context: Context, prefs: SharedPreferences): Class2 {
...
}
Solution 2:
Since you have already defined how to retrieve SharedPreferences from DataManagerModule class you can simply change
internalfunprovideClass2(context: Context): Class2 {
...
}
to
internalfunprovideClass2(sharedPreferences: SharedPreferences): Class2 {
...
}
Have another class extend the Application class and declare it to the AndroidManifest like so:
classApp: Application() {
lateinitvar dataManagerComponent: DataManagerComponent
overridefunonCreate() {
super.onCreate()
dataManagerComponent = DaggerDataManagerComponent.builder()
.dataManagerModule(DataManagerModule(this))
.anotherModule(AnotherModule("config1", 123))
.build()
}
}
Modify your component to include an inject function
@Singleton@Component(modules = arrayOf(DataManagerModule::class,
AnotherModule::class))
interfaceDataManagerComponent{
fungetDataManager() : DataManager
fungetSharedPreferences() : SharedPreferences
// The activity/fragment you will need the valuesfuninject(target: MainActivity)
}
Then inject it to the activity
classMainActivity : AppCompatActivity() {
@Injectlateinitvar class2: Class2
overridefunonCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
(application as App).dataManagerComponent.inject(this)
Log.i("CLASS2", class2.toString())
}
}
Post a Comment for "From One Dagger2 Module How To Access The Sharedpreferences Provided In Another Dagger2 Module"