func listenPost()

in FriendlyPix/FPFeedViewController.swift [458:506]


  func listenPost(_ post: FPPost) {
    let commentQuery: DatabaseQuery = self.commentsRef.child(post.postID)
    var lastCommentQuery = commentQuery
    let lastCommentId = post.comments.last?.commentID
    if let lastCommentId = lastCommentId {
      lastCommentQuery = commentQuery.queryOrderedByKey().queryStarting(atValue: lastCommentId)
    }
    lastCommentQuery.observe(.childAdded, with: { dataSnaphot in
      if dataSnaphot.key != lastCommentId {
        post.comments.append(FPComment(snapshot: dataSnaphot))
        if let index = self.posts.firstIndex(where: {$0.postID == post.postID}) {
          self.collectionView?.reloadItems(at: [IndexPath(item: index, section: 0)])
          self.collectionViewLayout.invalidateLayout()
        }
      }
    })
    commentQuery.observe(.childChanged, with: { dataSnaphot in
      if let index = post.comments.firstIndex(where: {$0.commentID == dataSnaphot.key}) {
        post.comments[index] = .init(snapshot: dataSnaphot)
        if let index = self.posts.firstIndex(where: {$0.postID == post.postID}) {
          self.collectionView?.reloadItems(at: [IndexPath(item: index, section: 0)])
          self.collectionViewLayout.invalidateLayout()
        }
      }
    })
    commentQuery.observe(.childRemoved, with: { dataSnaphot in
      if let index = post.comments.firstIndex(where: {$0.commentID == dataSnaphot.key}) {
        post.comments.remove(at: index)
        if let index = self.posts.firstIndex(where: {$0.postID == post.postID}) {
          self.collectionView?.reloadItems(at: [IndexPath(item: index, section: 0)])
          self.collectionViewLayout.invalidateLayout()
        }
      }
    })
    self.observers.append(commentQuery)
    self.observers.append(lastCommentQuery)
    let likesQuery = self.likesRef.child(post.postID)
    likesQuery.observe(.value, with: {
      let count = Int($0.childrenCount)
      if post.likeCount != count || post.isLiked != $0.hasChild(self.uid){
        post.likeCount = count
        post.isLiked = $0.hasChild(self.uid)
        if let index = self.posts.firstIndex(where: {$0.postID == post.postID}) {
          self.collectionView?.reloadItems(at: [IndexPath(item: index, section: 0)])
        }
      }
    })
    self.observers.append(likesQuery)
  }