How to Use KStore
Create your store
Initialise your stores and keep a reference to it in your app (preferably using DI so that they are reused)
KStore File
val store: KStore<Pet> = storeOf(file = Path("$appDir/my_cats.json"))
KStore Storage
val store: KStore<Pet> = storeOf(key = "my_cats")
Other configuration options
Everything you want is in factory methods
val store: KStore<Pet> = storeOf(
// For kstore-file with json
file = Path("$appDir/$fileName.json"),
// Or for kstore-storage
key = "$keyName",
storage = localStorage, // optional
// Or your own custom codec
codec = YourCustomCodec<Pet>(), // optional
// Returns this value if the file is not found. Defaults to null
default = null, // optional
// Maintain a cache. If set to false, it always reads from disk
enableCache = true, // optional
// For versioning
version = 0, // optional
migration = { version, jsonElement -> default }, // optional
// For kstore-file, the serializer to use.
serializer = Json {
ignoreUnknownKeys = true
encodeDefaults = true
}, // optional
)
Use your store
Given that you have a @Serializable
model and a value
@Serializable data class Pet(val name: String, val age: Int) // Any serializable
val mylo = Pet(name = "Mylo", age = 1)
Get value
Get a value once
val mylo: Pet? = store.get()
Or observe for changes
val pets: Flow<Pet?> = store.updates
Set value
store.set(mylo)
Update a value
store.update { pet: Pet? ->
pet?.copy(age = pet.age + 1)
}
Delete/Reset value
store.delete()
You can also reset a value back to its default (if set, see here)
store.reset()
Last modified: 06 November 2024