Search code examples
swiftfirebase-realtime-databaseobservers

iOS Firebase RTDB observer - remove observer for the path which is NOT existing any longer


So the below method is observing if the user node is existing. It is to force a user to logout when that user on another device has deleted her/his account.

The question is simple - once that node has been deleted, the observer belonging to that node is also deleted, and no need to manually remove that observer? Otherwise, I don't think it will be possible to remove that observer as that specific node is not existing. Any advice will be grateful!

    internal var userReference: DatabaseReference?
    // EDITED : Add handler
    internal var userReferenceHandle: DatabaseHandle?
    // EDITED
    func authStateObserver(completion: @escaping () -> Void) {
        guard let uid = Auth.auth().currentUser?.uid else { return }
        userReference = REFERENCE_USERS.child(uid)
        userReference?.observe(.value, with: { (snapshot) in
            print("deleted node: \(snapshot)")
            
            if !snapshot.exists() {
                print("snapshot does not exist and user has been deleted. Completion block should be implemented")

                // EDITED: Add remover as below
                self.userReference?.removeObserver(withHandle: self.userReferenceHandle!)
                // EDITED

                completion()
            } else {
                print("snapshot exist")
            }
        }, withCancel: nil)
    }

EDIT : Thanks to Puff's advice the observer is now being removed after doing his job. Tested with arbitrary node to see that it is removed properly. Please refer to above inserts in quoted //EDITED if anyone needs it.


Solution

  • The observer will stay active after the node is deleted, as somebody may later recreate the node.

    If you want to remove the observer, you'll have to do so from your code by keeping a handle to the observer when you attach it. For more on this see the Firebase documentation on detaching listeners or the code in this answer: Firebase 'Observe' called multiple times with Swift on iOS