Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in firebase how to remove all observers, rather than observers for a specific ref

Tags:

ios

firebase

I'm creating a firebase app with a signOut. My question is does

   class func signOut(callback:((error:NSError?)->Void)) {
        let ref = Firebase(url:firebaseHost)
        ref.unauth()
        ref.removeAllObservers()
        let err = UserCredentials.delete()
        callback(error:err)
    }

remove just observers for the root reference? I'd like to remove all observers that were set in other parts of the app for several different queries.

Do I have to let ref... and re-create all those references to then remove observers?

Does unauth disconnect and remove observers? Is there jusa simple disconnect method for the client?

like image 1000
MonkeyBonkey Avatar asked Apr 02 '15 11:04

MonkeyBonkey


2 Answers

to use removeAllObservers you must use the var you used to set the observer. This you have to do for every different path in firebase where you set observers. There is no possibilty to say "remove all observers for all paths".

like image 176
user1894278 Avatar answered Oct 03 '22 00:10

user1894278


Swift 3 with firebase library's latest version to the date of this answer.

In each view controller you use, you can have a variable that is a database reference to Firebase:

var ref: FIRDatabaseReference!

Then in your viewdidload method you initialize the reference:

 override func viewDidLoad() {
    super.viewDidLoad()

    self.ref = FIRDatabase.database().reference()
    self.ref.child("child").observeSingleEvent(of: .value, with: { (snapshot) -> Void in

                // observer code
            })
    // other code
 }

Then you can remove all observers for the reference in that ViewController when the user is no longer in it through the deinitializer

deinit {
    self.ref.child("child").removeAllObservers()
}

According to this link this is how deinit works:

A deinitializer is called immediately before a class instance is deallocated. You write deinitializers with the deinit keyword, similar to how intializers are written with the init keyword. Deinitializers are only available on class types.

It is also possible to obtain a UInt from specific observers and then remove them through:

// Assign the Uint to your var "handle"
self.handle = self.ref.child("child").observeSingleEvent(of: .value, with: { (snapshot) -> Void in


            })
// Use this to remove the observer when you are done
self.ref.child("child").removeObserver(withHandle: self.handle)

**It is important to notice observers are removed from the same child references you declared.

self.ref.removeAllObservers()

Won't work

**

It took some time for me to understand how it works... Hope it helps anyone out there.

like image 39
Manuel BM Avatar answered Oct 02 '22 22:10

Manuel BM