Last active
November 21, 2022 10:17
-
-
Save osipxd/262d2d7d593309f833bf9c1431074d32 to your computer and use it in GitHub Desktop.
Base Serializer class to store nullable values in DataStore
This file contains hidden or 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 java.io.InputStream | |
import java.io.OutputStream | |
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 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also DataStoreSerializer