从一个 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)
}
}
最佳答案
由于所有这些 Artifact 共享相同的范围,并且该组件是使用这两个模块构建的,因此您应该能够简单地将 SharedPreferences
作为参数添加到 provideClass2()
为了在 Class2
的构造中使用它,如下所示:
@Provides
@Singleton
internal fun provideClass2(context: Context, prefs: SharedPreferences): Class2 {
...
}
关于android - 从一个 dagger 2 模块如何访问另一个 dagger 2 模块中提供的 SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50108369/