Search code examples
androidkotlinsharedpreferences

How to get SharedPreferences in KoinComponent?


I'm using SharedPreferences in SettingsFragment:

val myPrefs = activity?.getSharedPreferences("myPrefs", Context.MODE_PRIVATE) ?: return
val testEnvEnabled = myPrefs.getBoolean(getString(R.string.saved_test_env_key), false)

This is working just fine.

Then I need to ready those preferences in object Api : KoinComponent {

I cannot get there context or activity.

Is there some another way to get information from shared preferences?

For me it's important just to save one information, if test env. is on or off.

I'm saving that information in SettingsFragment over switch.

Thank you


Solution

  • You can use Like this;

    class Api : KoinComponent {
        private val sharedPreferences by inject<SharedPreferences> {
            parametersOf("myPref")
        }
    
        fun test() {
            sharedPreferences.edit().putInt("Test", 1).commit()
        }
    
        fun get(): Int {
            return sharedPreferences.getInt("Test", -1)
        }
    }
    
    val sharedPreferences = module {
        factory { key ->
            androidContext().getSharedPreferences(key.get<String>(0), Context.MODE_PRIVATE)
        }
        factory {
            Api()
        }
    }
    
    class App : Application() {
        override fun onCreate() {
            super.onCreate()
            startKoin {
                androidContext(this@App)
                modules(sharedPreferences)
            }
        }
    }
    
    enter code here