Skip to content

Commit

Permalink
Provide convenience extension function
Browse files Browse the repository at this point in the history
  • Loading branch information
janseeger committed Mar 11, 2024
1 parent 2c5d7aa commit 2d820b3
Showing 1 changed file with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package de.sipgate.federmappe.realtimedb

import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.ValueEventListener
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> {
return callbackFlow {
val valueEventListener = object : ValueEventListener {
override fun onCancelled(error: DatabaseError) {
close(IllegalStateException(error.toException()))
}

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

if (decodedAppData != null) {
trySend(decodedAppData)
}
}
}

this@toObject.addValueEventListener(valueEventListener)

awaitClose { this@toObject.removeEventListener(valueEventListener) }
}
}

0 comments on commit 2d820b3

Please sign in to comment.