Skip to content

Instantly share code, notes, and snippets.

@castasat
Created November 29, 2019 07:49
Show Gist options
  • Save castasat/e7b72f6acc04668697d75ad3ec311e5c to your computer and use it in GitHub Desktop.
Save castasat/e7b72f6acc04668697d75ad3ec311e5c to your computer and use it in GitHub Desktop.
Usage in activity or fragment: private var variableName by SharedString { requireContext() }
import android.annotation.SuppressLint
import android.content.Context
import android.content.Context.MODE_PRIVATE
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class SharedString(private val context: () -> Context) : ReadWriteProperty<Any, String?> {
private val sharedPreferences by lazy {
with(context()) {
getSharedPreferences("${javaClass.simpleName}_stored_vars", MODE_PRIVATE)
}
}
override fun getValue(thisRef: Any, property: KProperty<*>): String? {
return sharedPreferences.getString(property.name, "")
}
@SuppressLint("ApplySharedPref")
override fun setValue(thisRef: Any, property: KProperty<*>, value: String?) {
// write immediately
sharedPreferences.edit().putString(property.name, value).commit()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment