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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With