Last active
July 15, 2020 18:54
-
-
Save yashovardhan99/a5be5499467b443b079a5965e1142a5e to your computer and use it in GitHub Desktop.
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
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