With Firebase, Swift removeObserver(withHandle does not remove the observer

If you have the following code:

var postsRef: FIRDatabaseReference!
var postRefHandle: FIRDatabaseHandle!
var query = FIRDatabaseQuery()

func addHandler() {

    self.postsRef = self.ref.child("posts")
    var count = 20
    self.query = self.postsRef.queryOrdered(byChild: "sortTimestamp")

    self.postRefHandle = self.query.queryLimited(toFirst: UInt(count)).observe(.childAdded, with: { snapshot in
        print(snapshot) 
    })
}

and at a later time you do this function

self.postsRef.removeObserver(withHandle: self.postRefHandle!)

It removes the observer. This is tested code.

To the second part of your question: querySingleEvent and observe do the same thing data wise but have different behaviors. They will both always get current data - modified by startAt, endAt, equalTo etc.

observeSingleEvent returns the data, does NOT leave an observer so you will not be notified if that data changes

observe returns the data and leaves an observer attached to the node and will notify you of future changes.

.childAdded: when any children are added to the node .childChanges: when any children change in the node .childRemoved: when a child is removed.


How I'm Able to Achieve this is by removing child reference.

var recentRef: FIRDatabaseReference!

recentRef.child("\(groupId)").observe(.value, with: { (snapshot) in

                    recentRef.removeAllObservers() // not_working
                    recentRef.child("\(groupId)").removeAllObservers() //working

                    if let obj = snapshot.value as? [String: AnyObject] {
                            //... code here
                    }
                })