Hi Brian, i'm trying to make my firebase as flat as possible, so i store the real post data in a new node with postId as the key, and query postId in user_post node eg. " - postId: 1" (dummy 1).
In this case, I need to query to get the postId first and then fire off anther ref.observeSingleEvent in side the query completion handler. Now, I got this weird situation when i append the post in the inner request closure, if some inner requests finish faster, it adds to the main thread queue earlier. Now the order of all the posts will get messed up. So i tried decrease the query limit number, I noticed that if the number is smaller than 6 everything works fine. so that is my current solution. I don't is there is any other good solution to this...
the code: // i add var isPaging to prevent multiple call at the same time
internal func paginatePosts() {
print("\n start paging")
isPaging = true
let ref = Database.database().reference().child("user_posts").child(uid)
var query = ref.queryOrderedByKey()
let queryNum: UInt = 4
if posts.count > 0 {
let value = posts.last?.postId
query = query.queryEnding(atValue: value)
}
query.queryLimited(toLast: queryNum).observeSingleEvent(of: .value, with: { (snapshot) in
self.refreshControl.endRefreshing()
guard var allObjects = snapshot.children.allObjects as? [DataSnapshot] else { return }
allObjects.reverse()
if allObjects.count == 1 || allObjects.count == 0 {
self.isPaging = false
self.isFinishedPaging = true
self.tableView.reloadData()
}
if self.posts.count > 0 && allObjects.count > 0 { allObjects.removeFirst() }
allObjects.forEach({ (snapshot) in
let postId = snapshot.key
print(postId)
Database.fetchPostWithPID(pid: postId, completion: { (post) in
self.posts.append(post)
print("inside: ", post.postId)
if allObjects.last == snapshot {
self.isPaging = false
self.tableView.reloadData()
}
})
})
}) { (err) in
print("Failed to paginate for posts:", err)
}
}