Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion docs/topics/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,47 @@ val store: KStore<Pet> = storeOf(
```
{ collapsible="true" collapsed-title="val store: KStore<Pet> = storeOf" }

You can also use binary codecs for storage (e.g. Protobuf, Cbor)

```kotlin
// Boilerplate implementation for a BinaryCodec
public class BinaryCodec<T : @Serializable Any>(
private val key: String,
private val format: BinaryFormat,
private val serializer: KSerializer<T>,
private val storage: Storage,
) : Codec<T> {
override suspend fun encode(value: T?) {
if (value != null) storage[key] = format.encodeToByteArray(serializer, value)
else storage.remove(key)
}

override suspend fun decode(): T? = storage[key]
?.let { format.decodeFromByteArray(serializer, it) }
}

// Protobuf implementation
public inline fun <reified T : @Serializable Any> ProtobufCodec(
key: String,
// Other formats can be found here: https://kotlinlang.org/api/kotlinx.serialization/
format: BinaryFormat = Protobuf,
storage: Storage = localStorage,
): BinaryCodec<T> = BinaryCodec(
key = key,
format = format,
serializer = format.serializersModule.serializer(),
storage = storage,
)

// Use the `Codec` to create a store
val store = KStore<Pet> = storeOf(
codec = ProtobufCodec<Pet>,
default = Pet(),
enableCache = true
)
```
{ collapsible="true" collapsed-title="// Boilerplate implementation for a BinaryCodec" }

## Use your store

Given that you have a `@Serializable` model and a value
Expand Down Expand Up @@ -92,4 +133,4 @@ You can also reset a value back to its default (if set, see [here](#other-config

```kotlin
store.reset()
```
```
Loading