Last active
January 20, 2021 11:48
-
-
Save Sloy/f68921a2ead6466e530ff4b18c180c4d to your computer and use it in GitHub Desktop.
Reading Firebase Database as Kotlin coroutines
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
/* | |
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! | |
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) | |
} |
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
Thanks, great.
The above seems to be for Firebase Firestore, Can similar solution possible for the Firebase realtime database?