friendzr app
friendzr app

Reputation: 1

observer takes time so the code skips it and results in the flag to be nil

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

Answers (1)

Jakob Mygind
Jakob Mygind

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

Related Questions