0

I have a pair of nested dispatch queues. For some reason the code inside the second one never gets fired:

dispatchGroupOne.notify(queue: .main) { [weak self] in
  // Gets here
  self?.dispatchGroupTwo.notify(queue: .main) {
    // Doesn't get here
  }
}

Even if I don't enter/leave dispatchGroupTwo, it just never will get fired. Why is this? It works when it's not nested:

dispatchGroupOne.notify(queue: .main) {
  // Gets here
}
dispatchGroupTwo.notify(queue: .main) {
  // Gets here
}

However, I want to specifically perform code only after both of the dispatch groups have been fired.

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
Tometoyou
  • 7,792
  • 12
  • 62
  • 108

1 Answers1

1

Without nesting you register the listen separately so every group will act according to it's submitted tasks ,while when you nest them , then the notify of the inner group will depend on the outer one plus whether or not the it's (the inner group) tasks ended/working when it's notify is added upon triggering the outer notify

    let dispatchGroupOne = DispatchGroup()
     
    let dispatchGroupTwo = DispatchGroup()
    
    let dispatchGroupThird = DispatchGroup()
     
    dispatchGroupThird.enter() 
    dispatchGroupOne.notify(queue: .main) {
       // Gets here
        dispatchGroupThird.leave()
    }
    
    dispatchGroupThird.enter()
    dispatchGroupTwo.notify(queue: .main) {
      // Gets here
        dispatchGroupThird.leave() 
    }
    
    dispatchGroupThird.notify(queue: .main) {
       // All groups are done
    }
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • So how do I achieve the firing of code only after both of the groups have fired, if I can't nest them? Or is there a better way to do this without dispatch groups? – Tometoyou Aug 22 '22 at 14:30
  • @Tometoyou why not a one group ? BTW one possible way is to use a 3rd group check answer – Shehata Gamal Aug 22 '22 at 14:50