Skip to content

Commit d047d88

Browse files
Merge remote-tracking branch 'origin/master' into default-hierarchy-template
2 parents 7a6f4c6 + 698451b commit d047d88

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

docs/topics/usage.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,47 @@ val store: KStore<Pet> = storeOf(
4949
```
5050
{ collapsible="true" collapsed-title="val store: KStore<Pet> = storeOf" }
5151

52+
You can also use binary codecs for storage (e.g. Protobuf, Cbor)
53+
54+
```kotlin
55+
// Boilerplate implementation for a BinaryCodec
56+
public class BinaryCodec<T : @Serializable Any>(
57+
private val key: String,
58+
private val format: BinaryFormat,
59+
private val serializer: KSerializer<T>,
60+
private val storage: Storage,
61+
) : Codec<T> {
62+
override suspend fun encode(value: T?) {
63+
if (value != null) storage[key] = format.encodeToByteArray(serializer, value)
64+
else storage.remove(key)
65+
}
66+
67+
override suspend fun decode(): T? = storage[key]
68+
?.let { format.decodeFromByteArray(serializer, it) }
69+
}
70+
71+
// Protobuf implementation
72+
public inline fun <reified T : @Serializable Any> ProtobufCodec(
73+
key: String,
74+
// Other formats can be found here: https://kotlinlang.org/api/kotlinx.serialization/
75+
format: BinaryFormat = Protobuf,
76+
storage: Storage = localStorage,
77+
): BinaryCodec<T> = BinaryCodec(
78+
key = key,
79+
format = format,
80+
serializer = format.serializersModule.serializer(),
81+
storage = storage,
82+
)
83+
84+
// Use the `Codec` to create a store
85+
val store = KStore<Pet> = storeOf(
86+
codec = ProtobufCodec<Pet>,
87+
default = Pet(),
88+
enableCache = true
89+
)
90+
```
91+
{ collapsible="true" collapsed-title="// Boilerplate implementation for a BinaryCodec" }
92+
5293
## Use your store
5394

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

93134
```kotlin
94135
store.reset()
95-
```
136+
```

0 commit comments

Comments
 (0)