Created
February 23, 2020 12:43
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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