Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Dispatch Group Notify get's called twice?

I'm trying to get my app to use dispatch groups to make sure all invites have been sent before continuing. I thought the notify callback only got called once all enters have a matching leave but mine appears to be getting called multiple times, here's my code:

    for invite in invites {
        dispatchGroup.enter()
        let ref = FIRDatabase.database().reference().child("users").child(invite.id).child("invites")
        print(invite)
        ref.updateChildValues([name: nameTextField.text!]) { (error, ref) -> Void in
            dispatchGroup.leave()

            dispatchGroup.notify(queue: DispatchQueue.main, execute: {
                print("YOYOYO")
            })
        }
    }

In my console I'm seeing 2 "YOYOYO"s which confused me. Can anybody let me know if I'm doing this incorrectly or are my assumptions wrong?

like image 600
MarksCode Avatar asked Dec 10 '22 13:12

MarksCode


1 Answers

You probably have two invites. Move dispatchGroup.notify out of the for loop if you want to get notified after all invites are processed:

for invite in invites {
    dispatchGroup.enter()
    let ref = FIRDatabase.database().reference().child("users").child(invite.id).child("invites")
    print(invite)
    ref.updateChildValues([name: nameTextField.text!]) { (error, ref) -> Void in
        dispatchGroup.leave()            
    }
}

dispatchGroup.notify(queue: DispatchQueue.main) {
    print("YOYOYO")
}
like image 137
shallowThought Avatar answered Jan 21 '23 12:01

shallowThought