Skip to content

Instantly share code, notes, and snippets.

@yashovardhan99
Last active July 15, 2020 18:54
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 yashovardhan99/a5be5499467b443b079a5965e1142a5e to your computer and use it in GitHub Desktop.
Save yashovardhan99/a5be5499467b443b079a5965e1142a5e to your computer and use it in GitHub Desktop.
fun getPosts(userId: String): Flow<List<Post>> {
val db = FirebaseFirestore.getInstance()
return callbackFlow {
val listenerRegistration = db.collection("users")
.document(userId)
.collection("posts")
.addSnapshotListener { querySnapshot: QuerySnapshot?, firebaseFirestoreException: FirebaseFirestoreException? ->
if (firebaseFirestoreException != null) {
cancel(message = "Error fetching posts",
cause = firebaseFirestoreException)
return@addSnapshotListener
}
val map = querySnapshot.documents.
.mapNotNull { it.toPost() }
offer(map)
}
awaitClose {
Log.d(TAG, "Cancelling posts listener")
listenerRegistration.remove()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment