Created
November 21, 2022 10:13
-
-
Save osipxd/dade3d053f4b6d1484808f89b1e54e56 to your computer and use it in GitHub Desktop.
DataStore Serializer using kotlinx-serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also DataStoreNullableSerializer