I have a ref and I only want to listen when new items are added (it's in viewWillAppear
below). When a new item is added newItemsButton appears. If nothing new is added to what already exists inside the db then the button should't appear.
The problem is as soon as the observer starts to observe, the newItemButton appears even though nothing new was added. What am I doing wrong?
db:
-posts
-postId_1
-postId_2
-postId_3
code:
var startKey: String?
let postsRef = Database.database().reference().child("posts")
let postsObserverRef = Database.database().reference().child("posts")
override func viewDidLoad() {
super.viewDidLoad()
paginate()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
listenForNewItems()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
postsObserverRef.removeAllObservers()
}
func listenForNewItems() {
postsObserverRef.observe(.childAdded) { (snapshot) in
let postId = snapshot.key
let isContained = self.dataSource.contains { $0.postId == postId }
if !isContained {
// show newItemsButton
}
}
}
func paginate() {
if startKey == nil {
postsRef.queryOrderedByKey().queryLimited(toLast: 20)
.observeSingleEvent(of: .value, with: { (snapshot) in
// fill datasource
})
} else {
postsRef.queryOrderedByKey().queryEnding(atValue: startKey).queryLimited(toLast: 21)
.observeSingleEvent(of: .value, with: { (snapshot) in
// fill datasource
})
}
}