Skip to content

Instantly share code, notes, and snippets.

@saqib-github-commits
Last active April 25, 2023 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saqib-github-commits/190fec63ea93ea7b3dfce9db0d343c5a to your computer and use it in GitHub Desktop.
Save saqib-github-commits/190fec63ea93ea7b3dfce9db0d343c5a to your computer and use it in GitHub Desktop.
fun readFirebaseRealtimeDatabaseFlow(): Flow<String> = callbackFlow {
val database = FirebaseDatabase.getInstance("<path of realtime database>")
val databaseRef = database.reference
val firebaseDataListeners = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
val value = dataSnapshot.value
Log.d(ContentValues.TAG, "Value is: $value")
trySend(value?.toString().orEmpty())
}
override fun onCancelled(error: DatabaseError) {
// Failed to read value
Log.w(ContentValues.TAG, "Failed to read value.", error.toException())
}
}
databaseRef.addValueEventListener(firebaseDataListeners)
awaitClose {
databaseRef.removeEventListener(firebaseDataListeners)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment