Reputation: 1
I created a function that returns a boolean however the observer takes time to connect which results in the code to skip it, it prints the print statement saying flag is nil then it enters the prints in the observer. is there a way to fix this?
func HidingHim(idlabel:String) -> Bool{
var flag:Bool?
var d = Database.database().reference().child("Users").child(idlabel).child("hidingUser")
var h = d.observeSingleEvent(of: .value) { (snapshot) in
if(snapshot.hasChild(Auth.auth().currentUser!.uid)){
flag = true
print("flag in observer is true")
}else{
flag = false
print("flag in observer is false")
}
}
print("flag is \(flag!)")
return flag!
}
Upvotes: 0
Views: 48
Reputation: 134
Your function is synchronous, but it seems observeSingleEvent
has an asynchronous callback. You'll at least need to wait for that callback, which means you can't return Bool synchronously, but instead use an asynchronous callback, which you can supply in the function signature e.g. func HidingHim(idlabel: String, completion: @escaping (_ flag: Bool) -> Void)
Inside your observer completion you can call completion
with the appropriate Bool value.
Something like
func hidingHim(idlabel: String, completion: @escaping (_ flag: Bool) -> Void) {
var d = Database.database().reference().child("Users").child(idlabel).child("hidingUser")
var subscription = d.observeSingleEvent(of: .value) { (snapshot) in
if(snapshot.hasChild(Auth.auth().currentUser!.uid)){
completion(true)
} else {
completion(false)
}
}
}
Depending on how your observable implementation is you might need to hold on to the subscription
returned when you observeSingleEvent, lest it dies before it observes any values. If your completion is never called, that would be why. then you need to return the subscriber and save it somewhere, to keep the subscription alive.
Upvotes: 1