我最近了解了 Koin。
我试图将我当前的项目从 Dagger 迁移到 Koin。
这样做时,我遇到了注入(inject) 的问题。 sharedPreferences 和 sharedPreferences 编辑器 在事件中。
以下是我在 中使用的代码 Dagger 注入(inject) 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()
我尝试将上述代码转换为 科因 像这样->
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()
}
}
现在我像这样在我的事件中注入(inject)依赖项->
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)
}
需要说明的是,上面的代码在文件 中。模块.kt
现在您可以轻松地注入(inject)创建的实例,例如 ->
private val sharedPreferences: SharedPreferences by inject()
private val sharedPreferencesEditor: SharedPreferences.Editor by inject()
确保以上实例为 值 而不是 变量 否则,inject() 方法将不起作用,因为这是惰性注入(inject)。
关于dependency-injection - 面临将 sharedPreferences 和 sharedPrefrencesEditor 添加到 Koin 模块的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54235274/