面临将 sharedPreferences 和 sharedPrefrencesEditor 添加到 Koin 模块的问题

Facing issues with adding sharedPreferences and the sharedPrefrencesEditor to Koin module

我最近才知道 Koin。 我试图将我当前的项目从 Dagger 迁移到 Koin。 这样做时,我遇到了在活动中注入 sharedPreferences 和 sharedPreferences editor 的问题。

以下是我在 Dagger 中用于注入 sharedPreferences 和 sharedPreferences 编辑器的代码 ->

    @Provides
    @AppScope
    fun getSharedPreferences(context: Context): SharedPreferences =
            context.getSharedPreferences("default", Context.MODE_PRIVATE)

    @SuppressLint("CommitPrefEdits")
    @Provides
    @AppScope
    fun getSharedPrefrencesEditor(context: Context): SharedPreferences.Editor =
            getSharedPreferences(context).edit()

我试图将上面提到的代码转换为 Koin 像这样 ->

val appModule = module {

    val ctx by lazy{ androidApplication() }

    single {
        ctx.getSharedPreferences("default", Context.MODE_PRIVATE)
    }

    single {
        getSharedPreferences(ctx).edit()
    }
}

我也试过这样实现的->

val appModule = module {

        single {
            androidApplication().getSharedPreferences("default", Context.MODE_PRIVATE)
        }

        single {
            getSharedPreferences(androidApplication()).edit()
        }
    }

现在我像这样在 activity 中注入依赖项 ->

val sharedPreferences: SharedPreferences by inject()

val sharedPreferencesEditor: SharedPreferences.Editor by inject()

但是当我启动我的应用程序并尝试使用它们时,我无法在首选项中读取或写入任何内容。

我对代码有什么问题有点困惑。 请帮我解决这个问题。

我想出了一个办法来处理这个问题。 希望这对寻找相同问题的人有所帮助。

问题的解决方法如下:

koin 模块定义将是这样的 ->

 val appModule = module {

    single{
        getSharedPrefs(androidApplication())
    }

    single<SharedPreferences.Editor> {
        getSharedPrefs(androidApplication()).edit()
    }
 }

fun getSharedPrefs(androidApplication: Application): SharedPreferences{
    return  androidApplication.getSharedPreferences("default",  android.content.Context.MODE_PRIVATE)
}

只是要清楚上面的代码在文件中 modules.kt

现在您可以轻松地注入创建的实例,例如 ->

private val sharedPreferences: SharedPreferences by inject()

private val sharedPreferencesEditor: SharedPreferences.Editor by inject()

确保上述实例是 val 而不是 var 否则 inject() 方法将无法工作,因为这是惰性注入。