Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facing issues with adding sharedPreferences and the sharedPrefrencesEditor to Koin module

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.

like image 804
Annsh Singh Avatar asked Jan 17 '19 11:01

Annsh Singh


1 Answers

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.

like image 81
Annsh Singh Avatar answered Oct 18 '22 22:10

Annsh Singh