Skip to content

Instantly share code, notes, and snippets.

@lomza
Last active April 29, 2018 08:33
Show Gist options
  • Save lomza/05420beb56ac97c6449d0d7644eb3167 to your computer and use it in GitHub Desktop.
Save lomza/05420beb56ac97c6449d0d7644eb3167 to your computer and use it in GitHub Desktop.
object AppPreferences {
private const val NAME = "SpinKotlin"
private const val MODE = Context.MODE_PRIVATE
private lateinit var preferences: SharedPreferences
// list of app specific preferences
private val IS_FIRST_RUN_PREF = Pair("is_first_run", false)
fun init(context: Context) {
preferences = context.getSharedPreferences(NAME, MODE)
}
/**
* SharedPreferences extension function, so we won't need to call edit() and apply()
* ourselves on every SharedPreferences operation.
*/
private inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
val editor = edit()
operation(editor)
editor.apply()
}
var firstRun: Boolean
// custom getter to get a preference of a desired type, with a predefined default value
get() = preferences.getBoolean(IS_FIRST_RUN_PREF.first, IS_FIRST_RUN_PREF.second)
// custom setter to save a preference back to preferences file
set(value) = preferences.edit {
it.putBoolean(IS_FIRST_RUN_PREF.first, value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment