Reputation: 467
I'm trying to fetch data from different documents through iteration and yet, I want to listen for update to know when a new data is added. Let's take the code below for instance. Theres a list of users who the current user is following, and in this case, I'm trying to get the list of posts from each of them. The code below actually iterates through and get the data. But when a new post is added by one of the users in this following list, the data is being duplicated. I came to realize that this happens because the list that holds the posts should be cleared. The issue is, at what line should it be cleared. Putting it in the for loop can only result to clearing each post data before fetching for another user in the following list. So, how?
FirebaseFirestore.getInstance()
.collection("Users")
.document(FirebaseAuth.getInstance().currentUser!!.uid)
.collection("Following").addSnapshotListener { snapshot, error ->
followingList.clear()
postList.clear()
if (error != null) {
Log.d("LOG", error.message!!)
} else {
for (i in snapshot!!.documents) {
followingList.add(i.id)
}
for (following in followingList) {
FirebaseFirestore.getInstance().collection("Users")
.document(following).collection("Posts")
.addSnapshotListener { value, error2 ->
if (error2 != null) {
Log.d("LOG", error2.message!!)
} else {
val posts = value!!.toObjects(Post::class.java)
for (post in posts) {
postList.add(post)
}
postAdapter.notifyDataSetChanged()
}
}
}
}
}
Upvotes: 0
Views: 56
Reputation: 184
I believe you need to add it right before val posts = value!!.toObjects(Post::class.java)
. This is because the outer listener is only listening to following updates. The inner one is listening to posts, so if there is a new post, the inner one is the only one notified and you never actually clear the list of posts. So something like,
var postList = hashMapOf<String, MutableList<Post>>() // <--- outside first snapshotListener
...
for (following in followingList) {
FirebaseFirestore.getInstance().collection("Users")
.document(following).collection("Posts")
.addSnapshotListener { value, error2 ->
postList[following]?.clear() // <--- clearing list of posts for this specific user id
if (error2 != null) {
Log.d("LOG", error2.message!!)
} else {
val posts = value!!.toObjects(Post::class.java)
postList[following] = posts // <---
...
That's just my first thought. Hopefully it works. 👍🏼
Upvotes: 1