Preferences serialization is a kotlinx.serialization format to serialize arbitrary objects in androids SharedPreferences.
The documentation can be found on the projects Github Page.
@Serializable
data class Person(val name: String, val age: Int, val children: List<Person> = emptyList())
val preferences = Preferences(sharedPreferences)
val abby = Person("Abby", 12)
val bob = Person("Bob", 10)
val charles = Person("Charles", 36, listOf(abby, bob))
preferences.encode("person", charles)
// ...
val person: Person = preferences.decode("person")
assertEquals(charles, person)
You can get the full code here.
val preferences = Preferences(sharedPreferences)
var someFlag: Boolean by preferences.asProperty(default = false)
fun someComputation() {
someFlag = true
}
someComputation()
if (!someFlag) { // reads value from SharedPreferences at key "someFlag"
fail()
}
You can get the full code here.
You need to apply the kotlinx.serialization plugin and add this library as dependency.
Kotlin DSL:
plugins {
kotlin("plugin.serialization") version "2.0.20"
}
repositories {
mavenCentral()
}
dependencies {
implementation("net.edwardday.serialization:kprefs:0.13.0")
}
Note: additional information to the serialization plugin can be found in the kotlinx.serialization repository.
- support for all primitive types
- support for double by encoding it to
- Float - with loss of precision
- String - with the string representation
- Long - with the bits representation
- support for double by encoding it to
- support nullability (stored in extra field)
- support for native
Set<String>
encoding - support for encoding classes
- support for sealed classes
- support for objects by encoding an object start with a Boolean
- support for property delegated properties
- support for synchronization (synchronize on every object read / write)
To build the library just run ./gradlew library:build
. To publish it to you local maven repository use
./gradlew library:publishToMavenLocal