Hi all, trying to use `kotlinx-serialization-json-...
# serialization
x
Hi all, trying to use
kotlinx-serialization-json-okio
like this in
commonMain
Copy code
class ValueStore<T: Any>(
  val path: Path,
  val serializer: Json = Json,
  ..
) {
  suspend inline fun <reified V: T> set(value: V?) = lock.withLock {
    stateFlow.emit(value)
    serializer.encodeToBufferedSink(value, FILE_SYSTEM.sink(path).buffer())
  }
}
And have a
commonTest
written up like
Copy code
private val store: ValueStore<Pet> = ValueStore(path = "test.json".toPath())

@Test
fun testWriteValue() = runTest {
  val mylo = Pet(name = "Mylo", age = 1, type = Cat)
  store.set(mylo)
  val actual: Pet? = store.get<Pet>()
  val expect: Pet = mylo
  assertSame(expect, actual)
}
This test is failing 🤔 Although, I can see the
test.json
file being created, but it is empty. Am I using this correctly? Full source here
👀 1
✅ 1
j
You need to
use
the result of
buffer()
Your bytes are being buffed in memory and then you never flush/close to push them to the underlying filesystem
Calling
use
will close which will flush first
x
i see - thanks for the quick reply 🙌 it works
was looking for some docs earlier, and digging through tests to find any use-cases but couldn't. Hopefully this will help someone out
Copy code
suspend inline fun <reified V: T> set(value: V?) = lock.withLock {
  stateFlow.emit(value)
  FILE_SYSTEM.sink(path).buffer().use { sink: BufferedSink ->
    serializer.encodeToBufferedSink(value, sink)
  }
}
I think is safe to reuse this buffer. Nope