### KStore quick usage example Source: https://xxfast.github.io/KStore/overview.html Shows how to define a serializable model, create a KStore backed by a file, perform get/set/update/delete operations, and observe updates via a Flow. ```kotlin import kotlin.io.path.Path import kotlinx.serialization.Serializable // Take any serializable model @Serializable data class Pet(val name: String, val age: Int) // Create a store val store: KStore = storeOf(file = Path("path/to/my_cats.json")) // Get, set, update or delete values val mylo: Pet? = store.get() store.set(mylo) store.update { pet: Pet? -> pet?.copy(age = pet.age + 1) } store.delete() // Observe for updates val pets: Flow = store.updates ``` -------------------------------- ### Desktop (JVM): Get user data and cache directories with appdirs Source: https://xxfast.github.io/KStore/using-platform-paths.html Uses harawata's appdirs to get platform-specific app directories. Defines `PACKAGE_NAME`, `VERSION`, and `ORGANISATION` constants, then gets `filesDir` and `cacheDir`. ```kotlin import java.nio.file.FileSystem const val PACKAGE_NAME = "io.github.xxfast.kstore" const val VERSION = "1.0" const val ORGANISATION = "xxfast" val filesDir = AppDirsFactory.getInstance().getUserDataDir(PACKAGE_NAME, VERSION, ORGANISATION) val cacheDir = AppDirsFactory.getInstance().getUserCacheDir(PACKAGE_NAME, VERSION, ORGANISATION) ``` -------------------------------- ### Binary Codec Implementation Source: https://xxfast.github.io/KStore/usage.html Example of boilerplate implementation for using binary codecs like Protobuf or Cbor. ```kotlin // Boilerplate implementation for a BinaryCodec {...} ``` -------------------------------- ### Android: Get files and cache paths from Context Source: https://xxfast.github.io/KStore/using-platform-paths.html Shows how to set `files` and `cache` in an Android `MainActivity` using `context.filesDir` and `context.cacheDir`. Requires importing `kotlin.io.path.Path`. ```kotlin import kotlin.io.path.Path class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) files = Path(context.filesDir) cache = Path(context.cacheDir) } } ``` -------------------------------- ### iOS & Apple platforms: Get documents and caches URLs Source: https://xxfast.github.io/KStore/using-platform-paths.html Uses `NSFileManager` to get `NSDocumentDirectory` and `NSCachesDirectory` URLs, then assigns `files` and `cache` from their paths. The source warns that `NSHomeDirectory()` is not suitable for physical devices. ```kotlin val fileManager:NSFileManager = NSFileManager.defaultManager val documentsUrl: NSURL = fileManager.URLForDirectory( directory = NSDocumentDirectory, appropriateForURL = null, create = false, inDomain = NSUserDomainMask, error = null )!! val cachesUrl:NSURL = fileManager.URLForDirectory( directory = NSCachesDirectory, appropriateForURL = null, create = false, inDomain = NSUserDomainMask, error = null )!! files = Path(documentsUrl.path) caches = Path(cachesUrl.path) ``` -------------------------------- ### Get values from list store Source: https://xxfast.github.io/KStore/usage-list-store.html Retrieve the entire list or a single element by index. getOrEmpty returns an empty list if the store is empty, and get returns null if the index is out of bounds. ```kotlin val pets: List = listStore.getOrEmpty() val pet: Pet? = listStore.get(0) ``` -------------------------------- ### Get Store Value Source: https://xxfast.github.io/KStore/usage.html Retrieve the current value from the store once. ```kotlin val mylo: Pet? = store.get() ``` -------------------------------- ### Map elements in list store Source: https://xxfast.github.io/KStore/usage-list-store.html Transform each element in the list store using map or mapIndexed. The examples show updating the age property of each pet. ```kotlin listStore.map { pet -> pet.copy(age = pet.age + 1) } listStore.mapIndexed { index, pet -> pet.copy(age = index) } ``` -------------------------------- ### Update Store Value Source: https://xxfast.github.io/KStore/usage.html Update the existing value using a transaction. This maintains a single mutex lock, which is safer than separate get and set calls. ```kotlin store.update { pet: Pet? -> pet?.copy(age = pet.age + 1) } ``` -------------------------------- ### Initialize KStore with Key Source: https://xxfast.github.io/KStore/usage.html Create a store instance using a simple key for storage. ```kotlin val store: KStore = storeOf(key = "my_cats") ``` -------------------------------- ### Initialize KStore with File Path Source: https://xxfast.github.io/KStore/usage.html Create a store instance using a specific file path. Ensure the appDir is configured correctly before use. ```kotlin val store: KStore = storeOf(file = Path("$appDir/my_cats.json")) ``` -------------------------------- ### Desktop (JVM): Create directories and assign paths Source: https://xxfast.github.io/KStore/using-platform-paths.html Creates the `files` directory if it doesn't exist using `SystemFileSystem`, then assigns `files` and `cache` from `filesDir` and `cacheDir`. The source notes that the store won't create directories for you. ```kotlin import kotlinx.io.files.Path import kotlinx.io.files.SystemFileSystem with(SystemFileSystem) { if(!exists(files)) createDirectories(files) } files = Path(filesDir) cache = Path(cacheDir) ``` -------------------------------- ### Configure Dependencies for Multiplatform including Web Source: https://xxfast.github.io/KStore/installation.html Split dependencies to use kstore-storage for browser targets, as they do not support a file system. ```kotlin sourceSets { val commonMain by getting { dependencies { implementation(libs.kstore) } } val androidMain by getting { dependencies { implementation(libs.kstore.file) } } val iosMain by getting { dependencies { implementation(libs.kstore.file) } } val jvmMain by getting { dependencies { implementation(libs.kstore.file) } } val jsMain by getting { dependencies { implementation(libs.kstore.storage) } } val wasmJsMain by getting { dependencies { implementation(libs.kstore.storage) } } ``` -------------------------------- ### Create KStore instances with platform-specific paths Source: https://xxfast.github.io/KStore/using-platform-paths.html Creates KStore instances for files and caches using the `files` and `cache` path variables. The paths are constructed with `Path("$files/my_cats.json")` and `Path("$cache/my_cats.json")`. ```kotlin val files: KStore = storeOf(file = Path("$files/my_cats.json")) val caches: KStore = storeOf(file = Path("$cache/my_cats.json")) ``` -------------------------------- ### Configure Dependencies for Android, iOS, and Desktop Source: https://xxfast.github.io/KStore/installation.html Include the kstore-file dependency in commonMain for platforms supporting a file system. ```kotlin sourceSets { val commonMain by getting { dependencies { implementation(libs.kstore.file) } } } ``` -------------------------------- ### Migrate binary incompatible versions with storeOf Source: https://xxfast.github.io/KStore/using-versioning.html Shows how to migrate data when models are binary incompatible. Defines CatV1, CatV2, and CatV3 with derived, new, and renamed fields, then uses storeOf with version = 3 and a when block to convert JSON from versions 1 and 2 into CatV3. ```kotlin @Serializable data class CatV1( val name: String, val lives: Int = 9, val cuteness: Int ) @Serializable data class CatV2( val name: String, val lives: Int = 9, val age: Int = 9 - lives, // derived field val kawaiiness: Long // new field ) @Serializable data class CatV3( val name: String, val lives: Int = 9, val age: Int = 9 - lives, val isCute: Boolean // renamed field ) val storeV3: KStore = storeOf(file = file, version = 3) { version, jsonElement -> when (version) { 1 -> jsonElement?.jsonObject?.let { val name = it["name"]!!.jsonPrimitive.content val lives = it["lives"]!!.jsonPrimitive.int val age = it["age"]?.jsonPrimitive?.int ?: (9 - lives) val isCute = it["cuteness"]!!.jsonPrimitive.int.toLong() > 1 CatV3(name, lives, age, isCute) } 2 -> jsonElement?.jsonObject?.let { val name = it["name"]!!.jsonPrimitive.content val lives = it["lives"]!!.jsonPrimitive.int val age = it["age"]?.jsonPrimitive?.int ?: (9 - lives) val isCute = it["kawaiiness"]!!.jsonPrimitive.long > 1 CatV3(name, lives, age, isCute) } else -> null } } ``` -------------------------------- ### Define KStore Dependencies in Version Catalog Source: https://xxfast.github.io/KStore/installation.html Define the KStore version and library modules in your version catalog file. ```toml [versions] kstore = "x.x.x" [libraries] kstore = { module = "io.github.xxfast:kstore", version.ref = "kstore" } kstore-file = { module = "io.github.xxfast:kstore-file", version.ref = "kstore" } kstore-storage = { module = "io.github.xxfast:kstore-storage", version.ref = "kstore" } ``` -------------------------------- ### KStore Factory Configuration Source: https://xxfast.github.io/KStore/usage.html Access additional configuration options through factory methods. ```kotlin val store: KStore = storeOf {...} ``` -------------------------------- ### Apache License 2.0 Source: https://xxfast.github.io/KStore/overview.html The full Apache License 2.0 text under which KStore is licensed. ```text Copyright 2023 Isuru Rajapakse Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` -------------------------------- ### Create a list store with listStoreOf Source: https://xxfast.github.io/KStore/usage-list-store.html listStoreOf is the same as storeOf but defaults to an empty list instead of null. This is an experimental API and may be removed in future releases. ```kotlin val listStore: KStore> = listStoreOf(file = Path("path/to/file")) ``` -------------------------------- ### Add KStore dependencies for common, file, and storage targets Source: https://xxfast.github.io/KStore/overview.html Declares the KStore dependencies in a version catalog: kstore for common code, kstore-file for Android, iOS, desktop, and Node.js, and kstore-storage for jsBrowser and wasmJsBrowser. ```toml # for common kstore = { module = "io.github.xxfast:kstore", version.ref = "kstore" } # for android, iOS, desktop and nodeJs kstore-file = { module = "io.github.xxfast:kstore-file", version.ref = "kstore" } # for jsBrowser and wasmJsBrowser kstore-storage = { module = "io.github.xxfast:kstore-storage", version.ref = "kstore" } ``` -------------------------------- ### Observe list store updates Source: https://xxfast.github.io/KStore/usage-list-store.html Observe the list as a Flow of List. updatesOrEmpty emits the current list and subsequent changes. ```kotlin val pets: Flow> = listStore.updatesOrEmpty ``` -------------------------------- ### Set Store Value Source: https://xxfast.github.io/KStore/usage.html Set a new value in the store. ```kotlin store.set(mylo) ``` -------------------------------- ### Define files and cache path variables Source: https://xxfast.github.io/KStore/using-platform-paths.html Declares top-level variables for file and cache paths. The source notes that a DI framework is recommended instead of top-level variables. ```kotlin var files: Path var cache: Path ``` -------------------------------- ### Add or remove elements from list store Source: https://xxfast.github.io/KStore/usage-list-store.html Use plus to add an element and minus to remove an element from the list store. ```kotlin listStore.plus(pet) listStore.minus(pet) ``` -------------------------------- ### Observe Store Updates Source: https://xxfast.github.io/KStore/usage.html Observe changes to the store value using a Flow. ```kotlin val pets: Flow = store.updates ``` -------------------------------- ### Add Maven Central repository Source: https://xxfast.github.io/KStore/overview.html Adds the Maven Central repository to your Gradle build, with an optional snapshot repository for snapshot builds. ```kotlin repositories { mavenCentral() // or for snapshot builds maven("https://central.sonatype.com/repository/maven-snapshots/") } ``` -------------------------------- ### Derive new fields without migrations Source: https://xxfast.github.io/KStore/using-versioning.html Shows how to derive new fields from existing ones without writing migrations. The age field is computed from lives, so no migration is needed. ```kotlin @Serializable data class CatV1(val name: String, val lives: Int = 9) @Serializable data class CatV2(val name: String, val lives: Int = 9, val age: Int = 9 - lives) ``` -------------------------------- ### Define Serializable Model Source: https://xxfast.github.io/KStore/usage.html Define a data class with the @Serializable annotation to be used with KStore. ```kotlin @Serializable data class Pet(val name: String, val age: Int) // Any serializable val mylo = Pet(name = "Mylo", age = 1) ``` -------------------------------- ### Reset Store Value Source: https://xxfast.github.io/KStore/usage.html Reset the store value back to its default. ```kotlin store.reset() ``` -------------------------------- ### Delete Store Value Source: https://xxfast.github.io/KStore/usage.html Remove the value from the store. ```kotlin store.delete() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.