Skip to content

Instantly share code, notes, and snippets.

Last active November 21, 2022 10:17
  • 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?
Base Serializer class to store nullable values in DataStore
import androidx.datastore.core.DataStore
import androidx.datastore.core.Serializer
abstract class NullableSerializer<T : Any> : Serializer<T?> {
override val defaultValue: T? = null
final override suspend fun readFrom(input: InputStream): T? {
return if (input.isNotEmpty()) readNotNullFrom(input) else null
final override suspend fun writeTo(t: T?, output: OutputStream) {
if (t != null) writeNotNullTo(t, output)
protected abstract fun readNotNullFrom(input: InputStream): T
protected abstract fun writeNotNullTo(t: T, output: OutputStream)
private fun InputStream.isNotEmpty() = available() > 0
suspend fun <T : Any> DataStore<T?>.clear() = updateData { null }
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