Skip to content

Instantly share code, notes, and snippets.

@Sloy
Last active January 20, 2021 11:48
Show Gist options
  • Save Sloy/f68921a2ead6466e530ff4b18c180c4d to your computer and use it in GitHub Desktop.
Save Sloy/f68921a2ead6466e530ff4b18c180c4d to your computer and use it in GitHub Desktop.
Reading Firebase Database as Kotlin coroutines
/*
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
WARNING!!!
NO, SERIOUSLY. REAL WARNING!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
This snippet was written years ago, when coroutines were experimental and I had no clue how did they work.
But for some reason my gist keep showing up first in some Google searches.
DO NOT USE THIS CODE.
Now there's official support for adapting Firebase methods to coroutines:
https://github.com/Kotlin/kotlinx.coroutines/tree/master/integration/kotlinx-coroutines-play-services
*/
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.experimental.CommonPool
import kotlinx.coroutines.experimental.async
import kotlin.coroutines.experimental.suspendCoroutine
suspend fun DatabaseReference.getValue(): DataSnapshot {
return async(CommonPool) {
suspendCoroutine<DataSnapshot> { continuation ->
addListenerForSingleValueEvent(FValueEventListener(
onDataChange = { continuation.resume(it) },
onError = { continuation.resumeWithException(it.toException()) }
))
}
}.await()
}
class FValueEventListener(val onDataChange: (DataSnapshot) -> Unit, val onError: (DatabaseError) -> Unit) : ValueEventListener {
override fun onDataChange(data: DataSnapshot) = onDataChange.invoke(data)
override fun onCancelled(error: DatabaseError) = onError.invoke(error)
}
@mochadwi
Copy link

mochadwi commented Mar 21, 2019

@pedromassango
Copy link

pedromassango commented Mar 28, 2019

This official implementation is not for Firebase Database! I've tried

@faisalmohd83
Copy link

Thanks, great.
The above seems to be for Firebase Firestore, Can similar solution possible for the Firebase realtime database?

@AhsenSaeed
Copy link

Hey, @faisalmohd83 you can use kotlin coroutines Flow API for firebase realtime database. Check out this https://ahsensaeed.com/android-firebase-kotlin-coroutines-flow-api/.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment