Skip to content

Instantly share code, notes, and snippets.

@osipxd
Created November 21, 2022 10:13
Show Gist options
  • Save osipxd/dade3d053f4b6d1484808f89b1e54e56 to your computer and use it in GitHub Desktop.
Save osipxd/dade3d053f4b6d1484808f89b1e54e56 to your computer and use it in GitHub Desktop.
DataStore Serializer using kotlinx-serialization
import androidx.datastore.core.DataStore
import androidx.datastore.core.Serializer
import kotlinx.coroutines.flow.first
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import kotlinx.serialization.json.encodeToStream
import java.io.InputStream
import java.io.OutputStream
/**
* DataStore Serializer using kotlinx-serialization.
* Default value is null.
*/
fun <reified T : Any> DataStoreSerializer(): Serializer<T?> {
return object : Serializer<T?> {
override val defaultValue: T? = null
override suspend fun readFrom(input: InputStream): T? {
return if (input.isNotEmpty()) {
Json.decodeFromStream(input)
} else {
null
}
}
override suspend fun writeTo(t: T?, output: OutputStream) {
if (t != null) Json.encodeToStream(t, output)
}
private fun InputStream.isNotEmpty() = available() > 0
}
}
suspend fun <T : Any> DataStore<T?>.clear(): T? = updateData { null }
suspend fun <T : Any> DataStore<T?>.requireValue(): T = checkNotNull(data.first())
@osipxd
Copy link
Author

osipxd commented Nov 21, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment