从一个 dagger2 模块提供 SharedPreferences 后,在另一个 dagger2 模块中想要使用它,
怎么做?
下面的代码似乎不起作用。
/** 组件 */
@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
,像这样:
@Provides
@Singleton
internal fun provideClass2(context: Context, prefs: SharedPreferences): Class2 {
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)