Skip to content

Instantly share code, notes, and snippets.

Created November 21, 2022 10:13
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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
* 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()) {
} else {
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())
Copy link

osipxd commented Nov 21, 2022

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