Skip to content

Instantly share code, notes, and snippets.

@kubode
Created May 25, 2016 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kubode/89d4b4327718caabf1f723926ff2527f to your computer and use it in GitHub Desktop.
Save kubode/89d4b4327718caabf1f723926ff2527f to your computer and use it in GitHub Desktop.
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class SharedPreferencesProperty<T>(val sharedPreferences: SharedPreferences,
val key: String,
val get: SharedPreferences.(String) -> T,
val put: SharedPreferences.Editor.(String, T) -> SharedPreferences.Editor) : ReadWriteProperty<Any, T> {
companion object {
fun of(sharedPreferences: SharedPreferences, key: String, defaultValue: String) =
SharedPreferencesProperty(sharedPreferences, key,
{ getString(it, defaultValue) }, SharedPreferences.Editor::putString)
fun of(sharedPreferences: SharedPreferences, key: String, defaultValue: Boolean) =
SharedPreferencesProperty(sharedPreferences, key,
{ getBoolean(it, defaultValue) }, SharedPreferences.Editor::putBoolean)
fun of(sharedPreferences: SharedPreferences, key: String, defaultValue: Int) =
SharedPreferencesProperty(sharedPreferences, key,
{ getInt(it, defaultValue) }, SharedPreferences.Editor::putInt)
}
override fun getValue(thisRef: Any, property: KProperty<*>): T {
return sharedPreferences.get(key)
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
sharedPreferences.edit().put(key, value).apply()
}
}
@ApplicationScope
class ApplicationPreferences @Inject constructor(context: Context) {
private val pref = context.getSharedPreferences("ApplicationPreferences", Context.MODE_PRIVATE)
var isTermsAgreed by SharedPreferencesProperty.of(pref, "isTermisAgreed", false)
var uuid by SharedPreferencesProperty.of(pref, "uuid", "")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment