user1480139
user1480139

Reputation: 383

Firebase observer still gets values even after removeObserver

I'm having a Firebase Handle like this:

private var typeIndicatorHandle: DatabaseHandle?
self.typeIndicatorHandle = self.dbRef.child("chats").child(chatId).child("typingIndicator").queryOrderedByValue().queryEqual(toValue: true).observe(.value, with: { (snapshot) in
            print("new value")
        })

somewhere else I do this:

if let typeIndicatorHandle = self.typeIndicatorHandle {
        self.dbRef.removeObserver(withHandle: typeIndicatorHandle)
    }

Now the problem is the observer still gets new values. How is that possible?

Upvotes: 0

Views: 23

Answers (1)

Mohammed Rampurawala
Mohammed Rampurawala

Reputation: 3112

You need to remove the observer on original children where you attached it.

For Example:

 private var typeIndicatorHandle: DatabaseHandle?
    private var dbRef:DatabaseReference?
self.childRef= self.dbRef.child("chats").child(chatId).child("typingIndicator").queryOrderedByValue().queryEqual(toValue: true)

    self.typeIndicatorHandle = childRef.observe(.value, with: { (snapshot) in
                print("new value")
            })

To Remove the listener:

if let typeIndicatorHandle = self.typeIndicatorHandle {
       self.childRef.removeObserver(withHandle: typeIndicatorHandle)
    }

Sorry for my bad syntax. I don't know swift that much in case of any correctness correct it.

But you need to remove the listener on the DatabaseReference on which you have added listener.

Upvotes: 1

Related Questions