Last active
June 19, 2020 18:36
-
-
Save egorshustov/d979ea2f4c1848c6fc8012cba6e017f7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 androidx.lifecycle.LiveData | |
class LivePreference<T>( | |
private val sharedPrefs: SharedPreferences, | |
private val key: String, | |
private val defValue: T | |
) : LiveData<T?>() { | |
private val preferenceChangeListener = | |
SharedPreferences.OnSharedPreferenceChangeListener { _, key -> | |
if (key == this.key) { | |
value = findPreference(key, defValue) | |
} | |
} | |
override fun onActive() { | |
super.onActive() | |
value = findPreference(key, defValue) | |
sharedPrefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener) | |
} | |
override fun onInactive() { | |
sharedPrefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener) | |
super.onInactive() | |
} | |
@Suppress("UNCHECKED_CAST") | |
private fun findPreference(key: String, defaultValue: T): T = with(sharedPrefs) { | |
val foundValue: Any = when (defaultValue) { | |
is String -> getString(key, defaultValue) | |
is Int -> getInt(key, defaultValue) | |
is Long -> getLong(key, defaultValue) | |
is Float -> getFloat(key, defaultValue) | |
is Boolean -> getBoolean(key, defaultValue) | |
else -> throw IllegalArgumentException("This type cannot be obtained from Preferences") | |
} | |
foundValue as T | |
} | |
fun putPreference(value: T?) = with(sharedPrefs.edit()) { | |
value ?: return@with | |
when (value) { | |
is String -> putString(key, value) | |
is Int -> putInt(key, value) | |
is Long -> putLong(key, value) | |
is Float -> putFloat(key, value) | |
is Boolean -> putBoolean(key, value) | |
else -> throw IllegalArgumentException("This type cannot be saved into Preferences") | |
}.apply() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment