将 sharedPreferences 和 sharedPrefencesEditor 添加到 Koin 模块时遇到的问题

Ann*_*ngh 4 dependency-injection koin

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

以下是我在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()
Run Code Online (Sandbox Code Playgroud)

我试图像这样将上述代码转换为Koin ->

val appModule = module {

    val ctx by lazy{ androidApplication() }

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

    single {
        getSharedPreferences(ctx).edit()
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试以这种方式实现它->

val appModule = module {

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

        single {
            getSharedPreferences(androidApplication()).edit()
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在我像这样在我的活动中注入依赖项 - >

val sharedPreferences: SharedPreferences by inject()

val sharedPreferencesEditor: SharedPreferences.Editor by inject()
Run Code Online (Sandbox Code Playgroud)

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

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

Ann*_*ngh 7

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

这是问题的解决方案:

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)
}
Run Code Online (Sandbox Code Playgroud)

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

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

private val sharedPreferences: SharedPreferences by inject()

private val sharedPreferencesEditor: SharedPreferences.Editor by inject()
Run Code Online (Sandbox Code Playgroud)

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