diff options
author | Allan Wang <me@allanwang.ca> | 2017-07-05 22:49:25 -0700 |
---|---|---|
committer | Allan Wang <me@allanwang.ca> | 2017-07-05 22:49:25 -0700 |
commit | 27fcb08588e5691b3dd419bd23603d79f0af484c (patch) | |
tree | b679bdbd435522f447038f2b251cc3388ce0fae0 /core/src/main/kotlin/ca/allanwang/kau/kpref/KPrefSingleDelegate.kt | |
parent | f5f0ef698634e37646eea8c5f3b067bdc1d14542 (diff) | |
download | kau-27fcb08588e5691b3dd419bd23603d79f0af484c.tar.gz kau-27fcb08588e5691b3dd419bd23603d79f0af484c.tar.bz2 kau-27fcb08588e5691b3dd419bd23603d79f0af484c.zip |
Create kpref single
Diffstat (limited to 'core/src/main/kotlin/ca/allanwang/kau/kpref/KPrefSingleDelegate.kt')
-rw-r--r-- | core/src/main/kotlin/ca/allanwang/kau/kpref/KPrefSingleDelegate.kt | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/core/src/main/kotlin/ca/allanwang/kau/kpref/KPrefSingleDelegate.kt b/core/src/main/kotlin/ca/allanwang/kau/kpref/KPrefSingleDelegate.kt new file mode 100644 index 0000000..58e570f --- /dev/null +++ b/core/src/main/kotlin/ca/allanwang/kau/kpref/KPrefSingleDelegate.kt @@ -0,0 +1,53 @@ +package ca.allanwang.kau.kpref + +import ca.allanwang.kau.kotlin.ILazyResettable + +/** + * Created by Allan Wang on 2017-06-07. + */ +fun KPref.kprefSingle(key: String) = KPrefSingleDelegate(key, this) + +/** + * Singular KPref Delegate for booleans + * When the shared pref is not initialized, it will return true then set the pref to false + * All subsequent retrievals will be false + * This is useful for one time toggles such as showcasing items + */ +class KPrefSingleDelegate internal constructor(private val key: String, private val pref: KPref, lock: Any? = null) : ILazyResettable<Boolean> { + + @Volatile private var _value: Boolean? = null + private val lock = lock ?: this + + init { + if (pref.prefMap.containsKey(key)) + throw KPrefException("$key is already used elsewhere in preference ${pref.PREFERENCE_NAME}") + pref.prefMap.put(key, this@KPrefSingleDelegate) + } + + override fun invalidate() { + _value = null + } + + override val value: Boolean + get() { + val _v1 = _value + if (_v1 != null) + return _v1 + + return synchronized(lock) { + val _v2 = _value + if (_v2 != null) { + _v2 + } else { + _value = pref.sp.getBoolean(key, true) + if (_value!!) pref.sp.edit().putBoolean(key, false).apply() + _value!! + } + } + } + + override fun isInitialized(): Boolean = _value != null + + override fun toString(): String = if (isInitialized()) value.toString() else "Lazy kPref $key not initialized yet." + +}
\ No newline at end of file |