Remove observer after value change in Firebase

2020-05-26 13:40发布

问题:

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)

回答1:

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.