Skip to content

Instantly share code, notes, and snippets.

@3llomi
Created April 14, 2019 18:09
Show Gist options
  • Save 3llomi/19226d21b421ca85afee04f20a5ad39c to your computer and use it in GitHub Desktop.
Save 3llomi/19226d21b421ca85afee04f20a5ad39c to your computer and use it in GitHub Desktop.
Kotlin Extensions to convert Firebase Database Ref or Query to Deferred that you can 'await' on
fun DatabaseReference.toDeffered(): Deferred<DataSnapshot> {
val deferred = CompletableDeferred<DataSnapshot>()
deferred.invokeOnCompletion {
if (deferred.isCancelled) {
// optional, handle coroutine cancellation however you'd like here
}
}
this.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
deferred.completeExceptionally(p0.toException())
}
override fun onDataChange(p0: DataSnapshot) {
deferred.complete(p0)
}
})
return deferred
}
fun Query.toDeffered(): Deferred<DataSnapshot> {
val deferred = CompletableDeferred<DataSnapshot>()
deferred.invokeOnCompletion {
if (deferred.isCancelled) {
// optional, handle coroutine cancellation however you'd like here
}
}
this.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
deferred.completeExceptionally(p0.toException())
}
override fun onDataChange(p0: DataSnapshot) {
deferred.complete(p0)
}
})
return deferred
}
val ref = FirebaseDatabase.getInstance().reference.child("users")
withContext(Dispatchers.Main) {
//TODO Handle Exceptions
val dataSnapshot = ref.toDeffered().await()
}
//OR
launch(Dispatchers.Main) {
//TODO Handle Exceptions
val dataSnapshot = ref.toDeffered().await()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment