/KStore

Research fork

Primary LanguageKotlinApache License 2.0Apache-2.0

Store

Build Kotlin

badge-android badge-ios badge-mac badge-watchos badge-tvos badge-jvm badge-linux badge-windows badge-js badge-nodejs

A tiny Kotlin multiplatform library that assists in saving and restoring objects to and from disk using kotlinx.coroutines, kotlinx.serialisation and okio. Inspired by RxStore

Features

  • 🔒 Read-write locks; with a mutex FIFO lock
  • 💾 In-memory caching; read once from disk and reuse
  • 🕺 Multiplatform!

Adding to your project

KStore is not yet published to Maven Central, but is available on sonatype snapshot repositories.

repositories {
  maven("https://s01.oss.sonatype.org/content/repositories/snapshots/")
}

Include the dependency in commonMain

sourceSets {
  val commonMain by getting {
    implementation("io.github.xxfast:kstore:0.1-SNAPSHOT")
  }
}

Usage

Given that you have a @Serializable model

@Serializable data class Pet(val name: String, val age: Int) // Any serializable
val mylo = Pet(name = "Mylo", age = 1)

Crate a store

val store: KStore<Pet> = storeOf("path/to/file")

For full configuration and platform instructions, see here

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)
}

Note: this maintains a single mutex lock transaction, unlike get() and a subsequent set()

Delete/Reset value

store.delete()

You can also reset a value back to its default (if set, see here)

store.reset()

Configurations

Everything you want is in the factory method

private val store: KStore<Pet> = storeOf(
  path = filePathTo("file.json"), // required
  default = null, // optional
  enableCache = true, // optional
  serializer = Json, // optional
)

Platform configurations

Getting a path to a file is different for each platform and you will need to define how this works for each platform

expect fun filePathTo(fileName: String): String

On Android

actual fun filePathTo(fileName: String): String = "${context.filesDir.path}/$fileName"

On iOS & other Apple platforms

actual fun filePathTo(fileName: String): String = "${NSHomeDirectory()}/$fileName"

On Desktop

This depends on where you want to save your files, but generally you should save your files in a user data directory. Here i'm using harawata's appdirs to get the platform specific app dir

actual fun filePathTo(fileName: String): String {
  // implementation("net.harawata:appdirs:1.2.1")
  val appDir: String = AppDirsFactory.getInstance().getUserDataDir(PACKAGE_NAME, VERSION, ORGANISATION)
  return "$appDir/$fileName"
}

On JS Browser

TODO

On NodeJS

TODO