Base Serializer class to store nullable values in DataStore
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 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