Home > Software design >  Nested dispatch queues not firing inner dispatch queue
Nested dispatch queues not firing inner dispatch queue

Time:08-24

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.

CodePudding user response:

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
    }
  • Related