I recently got to know about Koin. I was trying to migrate my current project from Dagger to Koin. In doing so, I faced an issue with injecting sharedPreferences and sharedPreferences editor in the activities.
Following is the code I used in Dagger to inject sharedPreferences and sharedPreferences editor ->
@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()
I tried to convert the above mentioned code to Koin like this ->
val appModule = module {
val ctx by lazy{ androidApplication() }
single {
ctx.getSharedPreferences("default", Context.MODE_PRIVATE)
}
single {
getSharedPreferences(ctx).edit()
}
}
I also tried to implement it this way ->
val appModule = module {
single {
androidApplication().getSharedPreferences("default", Context.MODE_PRIVATE)
}
single {
getSharedPreferences(androidApplication()).edit()
}
}
Now I inject the dependencies in my activity like this ->
val sharedPreferences: SharedPreferences by inject()
val sharedPreferencesEditor: SharedPreferences.Editor by inject()
But as soon as I launch my app and try to use them, I am not able to read or write anything to the preferences.
I am a bit confused as to what is wrong with the code. Kindly help me figure this out.
I figured out a way to handle this. Hope this helps someone looking for the same issue.
Here is the solution to the problem:
The koin module definition will be like this ->
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)
}
Just to be clear that the above code is in the file modules.kt
Now you can easily inject the created instances like ->
private val sharedPreferences: SharedPreferences by inject()
private val sharedPreferencesEditor: SharedPreferences.Editor by inject()
Make sure the above instances are val instead of var otherwise the inject() method will not work as this is lazy injection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With