Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
- val editor = this.edit()
- operation(editor)
- editor.apply()
- }
- open class PreferenceRepository(val gson: Gson, val sharedPreferences: SharedPreferences) {
- operator inline fun <reified T> get(key: DefaultKey<T>, defaultValue: T? = null): T? {
- val value = sharedPreferences.getString(key.key, "")
- return if (value.isEmpty()) {
- defaultValue
- } else {
- try {
- gson.fromJson(value, T::class.java)
- } catch (e: Exception) {
- defaultValue
- }
- }
- }
- operator inline fun <reified T> set(key: DefaultKey<T>, value: T?) {
- sharedPreferences.edit {
- it.putString(key.key, gson.toJson(value))
- }
- }
- }
Add Comment
Please, Sign In to add comment