0

Needed some advice/review on possible downsides of using a dispatch group inside another group, if it could lead to a race condition/deadlock or just wrong practice.

1) Can a dispatch_group_enter exist inside the scope of another group? I could not find an example from Apple following such practice. Remember, secondCall needs to happen after firstCall. There is a dependency. Thoughts?

2) What would be a good design to execute a thirdCall - which again depends on result of firstCall result. But agnostic of the completionHandler timing i.e. can happen later and doesn't need to wait for completionHandler to finish.

Here's a simplified example of the completion handler incorporating 3 calls -

-(void)someMethod:(void (^)(NSError *error))completionHandler {

    dispatch_group_t serviceGroup = dispatch_group_create();

    dispatch_group_enter(serviceGroup);
    __typeof__(self) __weak weakSelf = self;
    [self.obj firstCall completion:^(NSError *firstError) {
        __typeof__(self) strongSelf = weakSelf;

        // Second Call
        if (!firstError.code) {
            dispatch_group_enter(serviceGroup);
            [strongSelf.obj secondCall completion:^(void) {
                dispatch_group_leave(serviceGroup);
            }];
        }

        // Third call
        if (!firstError.code) {
            [strongSelf executeThirdCall];
        }

        dispatch_group_leave(serviceGroup);
    }]; // Closing block for first call.

    dispatch_group_notify(serviceGroup, dispatch_get_main_queue(), ^{
        if (completionHandler) {
            completionHandler(error);
        }
    });
}

Some classic examples of dispatch groups can be found in this answer.

Community
  • 1
  • 1
raurora
  • 3,623
  • 1
  • 22
  • 29

1 Answers1

0

I can't think of any issues with this code.

However I am not sure you need dispatch groups at all for this example. You are executing three requests. Request 2 and Request 3 both depend on the result of the Request 1. You need to call the function's completionHandler when Request 2 is finished. Can't you do it into the completion handler of Request 2?

itskoBits
  • 435
  • 4
  • 13
  • Your understanding is correct. But last line is not clear?! "Can't you do it into the completion handler of Request 2" - the entire method is a completion handler - its a classic example of GCD dispatch groups where there is a dependency. – raurora Jun 27 '16 at 21:36