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

Overview

Store

Build Kotlin Maven Central

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 published on Maven Central

repositories { 
  mavenCentral()
}

Include the dependency in commonMain. Latest version Maven Central

sourceSets {
  val commonMain by getting {
    implementation("io.github.xxfast:kstore:<version>")
  }
}

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)

Create 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()

Lists

KStore provides you with some convenient extensions to manage stores that contain lists.

Create a list store

val listStore: KStore<List<Pet>> = listStoreOf("path/to/file") // same as [storeOf], but defaults to empty list

Get values

val pets: List<Cat> = store.getOrEmpty()
val pet: Cat = store.get(0)

or observe values

val pets: Flow<List<Cat>> = store.updatesOrEmpty

Add or remove elements

store.plus(cat)
store.minus(cat)

Map elements

store.map { cat -> cat.copy(cat.age = cat.age + 1) }
store.mapIndexed { index, cat -> cat.copy(cat.age = index) }

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

Licence

Copyright 2021 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.
You might also like...
Type-safe arguments for JetPack Navigation Compose using Kotlinx.Serialization

Navigation Compose Typed Compile-time type-safe arguments for JetPack Navigation Compose library. Based on KotlinX.Serialization. Major features: Comp

Android Parcelable support for the Kotlinx Serialization library.
Android Parcelable support for the Kotlinx Serialization library.

Android Parcelable support for the Kotlinx Serialization library.

Kotlin tooling for generating kotlinx.serialization serializers for serializing a class as a bitmask

kotlinx-serialization-bitmask Kotlin tooling for generating kotlinx.serialization serializers for serializing a class as a bitmask. Example @Serializa

CSV and FixedLength Formats for kotlinx-serialization

Module kotlinx-serialization-csv Serialize and deserialize ordered CSV and Fixed Length Format Files with kotlinx-serialization. Source code Docs Inst

Android Bundle format support for Kotlinx Serialization.

Bundlizer Android Bundle format support for Kotlinx Serialization. Usage Annotate your data models with @Serializable: import kotlinx.serialization.Se

Minecraft NBT support for kotlinx.serialization

knbt An implementation of Minecraft's NBT format for kotlinx.serialization. Technical information about NBT can be found here. Using the same version

KotlinX Serialization Standard Serializers (KS3)

KotlinX Serialization Standard Serializers (KS3) This project aims to provide a set of serializers for common types. ⚠️ Consider this project to be Al

Architecture With MVI using Kotlin, Coroutines, Retrofit and Unit test
Architecture With MVI using Kotlin, Coroutines, Retrofit and Unit test

Architecture With MVI using Kotlin, Coroutines, Retrofit and Unit test MVI (Model-View-Intent) streamlines the process of creating and developing appl

FaceTimeClone app that implements Coroutines , mvvm architecture , clean architecture , navigation component , hilt , etc.... using kotlin language
FaceTimeClone app that implements Coroutines , mvvm architecture , clean architecture , navigation component , hilt , etc.... using kotlin language

This repository contains a FaceTimeClone app that implements Coroutines , mvvm architecture , clean architecture , navigation component , hilt , etc.... using kotlin language

Comments
  • Gradle build improvements

    Gradle build improvements

    Hi, here are some build config improvements that will make the project build faster.

    • Update Gradle to 7.5.1
    • use Gradle Build Cache (this should really improve the build speed!)
    • use official Gradle GitHub Action (this supports Gradle build cache across builds, which again will improve build speeds)
    • disable some Gradle/Kotlin warnings, and remove some old properties
    opened by aSemy 3
  • Add folder implementation and tests

    Add folder implementation and tests

    KFolder lets you manage folders similar to how KStore lets you manage files. Useful when you have lots of data and when you need random access with a given index

    opened by xxfast 1
  • Unable to get a previously stored value if a default is set

    Unable to get a previously stored value if a default is set

    For example

    FILE_SYSTEM.sink(filePath.toPath()).buffer().use { Json.encodeToBufferedSink(OREO, it) }
    val store: KStore<Cat> = storeOf(filePath = filePath, default = MYLO)
    store.get() // Returns MYLO but should be OREO
    
    bug 
    opened by xxfast 0
  • How to handle migrations?

    How to handle migrations?

    If I have stored an object and need to alter the structure of the class, how can I migrate the existing data to the new structure? Do you support this?

    Some users might take a long time to download the latest update of an app, I must thus be able to migrate between from e.g. v1 to v5 of a data structure. Do you support this?

    enhancement 
    opened by Benjiko99 2
Releases(0.1.1)
  • 0.1.1(Oct 21, 2022)

    What's Changed

    • Fix get previously stored when a default is set by @xxfast in https://github.com/xxfast/KStore/pull/7
    • Bump android target sdk

    Full Changelog: https://github.com/xxfast/KStore/compare/0.1...0.1.1

    Source code(tar.gz)
    Source code(zip)
  • 0.1(Oct 2, 2022)

    What's Changed

    • Add KStore and test cases by @xxfast
    • Gradle build improvements by @aSemy in https://github.com/xxfast/KStore/pull/1
    • Add generic type store read and write test cases by @xxfast in https://github.com/xxfast/KStore/pull/2
    • Add list store by @xxfast in https://github.com/xxfast/KStore/pull/3

    New Contributors

    • @aSemy made their first contribution in https://github.com/xxfast/KStore/pull/1
    • @xxfast made their first contribution in https://github.com/xxfast/KStore/pull/2

    Full Changelog: https://github.com/xxfast/KStore/commits/0.1

    Source code(tar.gz)
    Source code(zip)
Owner
Isuru Rajapakse
Android developer @Gridstone & @MotorolaSolutions
Isuru Rajapakse
An tool to help developer to use Retrofit elegantly while using kotlinx.coroutines.

one An tool to help developer to use Retrofit elegantly while using kotlinx.coroutines. Feature Transform different data structs to one. {errorCode, d

ChengTao 30 Dec 27, 2022
Disk Usage/Free Utility - a better 'df' alternative

duf Disk Usage/Free Utility (Linux, BSD, macOS & Windows) Features User-friendly, colorful output Adjusts to your terminal's theme & width Sort the re

Christian Muehlhaeuser 10.3k Dec 31, 2022
Automatic CoroutineDispatcher injection and extensions for kotlinx.coroutines

Dispatch Utilities for kotlinx.coroutines which make them type-safe, easier to test, and more expressive. Use the predefined types and factories or de

Rick Busarow 132 Dec 9, 2022
Small Kafka Playground to play around with Test Containers, and KotlinX Coroutines bindings while reading Kafka Definite Guide V2

KafkaPlayground Small playground where I'm playing around with Kafka in Kotlin and the Kafka SDK whilst reading the Kafka book Definite Guide from Con

Simon Vergauwen 34 Dec 30, 2022
ShapeShift️ - A Kotlin library for intelligent object mapping and conversion between objects

ShapeShift️ A Kotlin library for intelligent object mapping and conversion between objects. Documentation Installation Maven Gradle Groovy DSL Kotlin

KRUD 127 Dec 7, 2022
A kotlin library of extension functions that add smalltalk style methods to objects.

KtTalk A kotlin library of extension functions that add smalltalk style methods to objects. Motivation Smalltalk is a pure OO language in which everyt

null 11 Oct 16, 2021
Recycler-coroutines - RecyclerView Auto Add Data Using Coroutines

Sample RecyclerView Auto Add With Coroutine Colaborator Very open to anyone, I'l

Faisal Amir 8 Dec 1, 2022
🍭 GithubSearchKMM - Github Repos Search - Android - iOS - Kotlin Multiplatform Mobile using Jetpack Compose, SwiftUI, FlowRedux, Coroutines Flow, Dagger Hilt, Koin Dependency Injection, shared KMP ViewModel, Clean Architecture

GithubSearchKMM Github Repos Search - Kotlin Multiplatform Mobile using Jetpack Compose, SwiftUI, FlowRedux, Coroutines Flow, Dagger Hilt, Koin Depend

Petrus Nguyễn Thái Học 50 Jan 7, 2023
Server Sent Events (SSE) client multiplatform library made with Kotlin and backed by coroutines

OkSSE OkSSE is an client for Server Sent events protocol written in Kotlin Multiplatform. The implementation is written according to W3C Recommendatio

BioWink GmbH 39 Nov 4, 2022
Opinionated Redux-like implementation backed by Kotlin Coroutines and Kotlin Multiplatform Mobile

CoRed CoRed is Redux-like implementation that maintains the benefits of Redux's core idea without the boilerplate. No more action types, action creato

Kittinun Vantasin 28 Dec 10, 2022