本文介绍了从一个dagger2模块中如何访问另一个dagger2模块中提供的SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
具有从一个dagger2模块提供的SharedPreferences,在另一个dagger2模块中想使用它,
怎么做?
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.
/**组件*/
@Singleton
@Component(modules = arrayOf(DataManagerModule::class,
AnotherModule::class))
interface DataManagerComponent {
fun getDataManager() : DataManager
fun getSharedPreferences() : SharedPreferences
}
/**模块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)
}
}
/**模块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)
}
}
推荐答案
由于所有这些工件都具有相同的作用域,并且该组件是使用两个模块构建的,因此您应该能够简单地将SharedPreferences
作为参数添加到provideClass2()
以便在Class2
的构造中使用它,就像这样:
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 {
...
}
这篇关于从一个dagger2模块中如何访问另一个dagger2模块中提供的SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!