-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Provide convenience extension function
- Loading branch information
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
46 changes: 46 additions & 0 deletions
46
realtimedb/src/main/kotlin/de/sipgate/federmappe/realtimedb/DatabaseReferenceExt.kt
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
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) } | ||
} | ||
} | ||
|