Skip to content

Instantly share code, notes, and snippets.

@DHosseiny
Created February 23, 2020 12:43
Show Gist options
  • Save DHosseiny/b69e3abb88355060cab25851c20fc1b6 to your computer and use it in GitHub Desktop.
Save DHosseiny/b69e3abb88355060cab25851c20fc1b6 to your computer and use it in GitHub Desktop.
Delegates for SharedPreferences(Copy paste usage) (Maybe add some other delegates for other types soon)
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
abstract class BasePreferencesDataSource {
protected abstract val preferences : SharedPreferences
protected class StringPrefProperty(private val key: String) : ReadWriteProperty<BasePreferencesDataSource, String> {
override fun getValue(thisRef: BasePreferencesDataSource, property: KProperty<*>): String {
return thisRef.preferences.getString(key, "")!!
}
override fun setValue(thisRef: BasePreferencesDataSource, property: KProperty<*>, value: String) {
thisRef.preferences.edit().putString(key, value).apply()
}
}
}
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
class PreferencesDataSource(context: Context) : BasePreferencesDataSource() {
override val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val aPreference by StringPrefProperty(PREF_SAMPLE_KEY)
companion object {
private const val PREF_SAMPLE_KEY = "sample_key"
}
}
class SampleClass(private val preferencesDataSource: PreferencesDataSource) {
fun someMethod() {
//some code
val preference: String = preferencesDataSource.aPreference
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment