Skip to content

Commit

Permalink
Simplify DatabaseReference extension properties
Browse files Browse the repository at this point in the history
  • Loading branch information
janseeger committed Mar 12, 2024
1 parent 4bd06ed commit 76ae0d6
Showing 1 changed file with 4 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,9 @@ import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.serializer

@ExperimentalSerializationApi
inline fun <reified T : Any> DatabaseReference.toObject(
serializer: KSerializer<T> = serializer<T>(),
crossinline errorHandler: (Throwable) -> T? = { throw it }
): Flow<T?> = callbackFlow {
val valueEventListener = object : ValueEventListener {
Expand All @@ -23,14 +19,7 @@ inline fun <reified T : Any> DatabaseReference.toObject(
}

override fun onDataChange(dataSnapshot: DataSnapshot) {
val decodedAppData =
try {
dataSnapshot.toObjectWithSerializer(serializer)
} catch (ex: SerializationException) {
errorHandler(ex)
}

trySend(decodedAppData)
trySend(dataSnapshot.toObject<T>(errorHandler = errorHandler))
}
}

Expand All @@ -41,7 +30,6 @@ inline fun <reified T : Any> DatabaseReference.toObject(

@ExperimentalSerializationApi
inline fun <reified T : Any> DatabaseReference.toObjects(
serializer: KSerializer<T> = serializer<T>(),
crossinline errorHandler: (Throwable) -> T? = { throw it }
): Flow<List<T>> = callbackFlow {
val valueEventListener = object : ValueEventListener {
Expand All @@ -50,15 +38,9 @@ inline fun <reified T : Any> DatabaseReference.toObjects(
}

override fun onDataChange(dataSnapshot: DataSnapshot) {
val decodedAppData = dataSnapshot.children.mapNotNull { childSnapshot ->
try {
childSnapshot.toObjectWithSerializer(serializer)
} catch (ex: SerializationException) {
errorHandler(ex)
}
}

trySend(decodedAppData)
trySend(dataSnapshot.children.mapNotNull { childSnapshot ->
childSnapshot.toObject<T>(errorHandler = errorHandler)
})
}
}

Expand Down

0 comments on commit 76ae0d6

Please sign in to comment.