Created
October 20, 2018 13:47
-
-
Save tobiasschuerg/4d19161638f8dd5d7551b58ab96c353d to your computer and use it in GitHub Desktop.
Kotlin Delegate for persistant objects
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
package com.tobiasschuerg | |
import android.content.SharedPreferences | |
import com.google.gson.Gson | |
import com.google.gson.GsonBuilder | |
import kotlin.properties.ReadWriteProperty | |
import kotlin.reflect.KProperty | |
class GsonDelegatePref<T>( | |
private val prefs: SharedPreferences, | |
private val name: String, | |
private val typeOfT: Class<T>, | |
private val default: (() -> T?) = { null } | |
) : ReadWriteProperty<Any?, T?> { | |
override fun getValue(thisRef: Any?, property: KProperty<*>): T? { | |
val json: String? = prefs.getString(name, null) | |
return if (json != null) { | |
gson.fromJson(json, typeOfT) | |
} else { | |
default() | |
} | |
} | |
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) { | |
val json: String? = value?.let { gson.toJson(value) } | |
prefs.edit().putString(name, json).apply() | |
} | |
companion object { | |
private val gson: Gson = GsonBuilder().setPrettyPrinting().create() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment