android - 从一个 dagger 2 模块如何访问另一个 dagger 2 模块中提供的 SharedPreferences

标签 android kotlin dagger-2

从一个 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/

相关文章:

android - ADB Shell挂载/卸载SD卡

Android - 如何仅通过单击应用程序图标来执行项目的主要功能?

android - 在 Android 中设置 Dagger 2 和项目组织

android - 如何在dagger 2中使子组件单例化?

android自定义通知不适用于约束布局

android - Dagger 2 : Is it recommended to use a static provider for Activities and fragments?

android - 如何限制在 android 中特定日期后再次发生警报?

android - 如何使用现有的 Realm 作为资源

Kotlin:使用 parcelize 时的构造函数

json - 使用 kotlinx.serialization 将 json 对象属性反序列化为字符串