Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove observer after value change in Firebase

I have global observer in ViewController and need some different observers inside it for specific values like one below. Is it possible to remove observer after value change once?

var ref = Firebase(url: "https://<FIREBASE-APP>.firebaseio.com/")

let handle = ref.observeEventType(.Value, withBlock: { snapshot in

    //Here VALUE Changes to NEW_VALUE
    if snapshot.value as! String == NEW_VALUE {

        //IS IT POSSIBLE TO REMOVE HANDLE HERE????
        ...something here
    }

})

//NOT HERE
...ref.removeObserverWithHandle(handle)
like image 283
Eugene G. Avatar asked Apr 11 '16 04:04

Eugene G.


1 Answers

This is one of the cases where you need to take an extra step in Swift, since it doesn't realize that you can safely access handle inside the block.

One way of working around this is:

let ref = Firebase(url: "https://yours.firebaseio.com/")
var handle: UInt = 0
handle = ref.observeEventType(.Value, withBlock: { snapshot in
    print(snapshot)
    if snapshot.exists() && snapshot.value as! String == "42" {
        print("The value is now 42")
        ref.removeObserverWithHandle(handle)
    }
})

By explicitly initializing the handle variable, we remove the error from the Swift compiler. But given that the handle will have been set before our block is invoked, we can safely call ref.removeObserverWithHandle(handle) inside the block.

like image 176
Frank van Puffelen Avatar answered Nov 03 '22 23:11

Frank van Puffelen