Skip to content

Instantly share code, notes, and snippets.

@jonlidgard
Created September 2, 2016 09:55
Show Gist options
  • Select an option

  • Save jonlidgard/9cd25b87d7e0570daa96d1b008d2084a to your computer and use it in GitHub Desktop.

Select an option

Save jonlidgard/9cd25b87d7e0570daa96d1b008d2084a to your computer and use it in GitHub Desktop.
Sequencing multiple async operations
#From CommandShift - © Richard Turton 2016
-(void)fetchConfigurationWithCompletion:(void (^)(NSError* error))completion
{
// Define errors to be processed when everything is complete.
// One error per service; in this example we'll have two
__block NSError *configError = nil;
__block NSError *preferenceError = nil;
// Create the dispatch group
dispatch_group_t serviceGroup = dispatch_group_create();
// Start the first service
dispatch_group_enter(serviceGroup);
[self.configService startWithCompletion:^(ConfigResponse *results, NSError* error){
// Do something with the results
configError = error;
dispatch_group_leave(serviceGroup);
}];
// Start the second service
dispatch_group_enter(serviceGroup);
[self.preferenceService startWithCompletion:^(PreferenceResponse *results, NSError* error){
// Do something with the results
preferenceError = error;
dispatch_group_leave(serviceGroup);
}];
dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
// Assess any errors
NSError *overallError = nil;
if (configError || preferenceError)
{
// Either make a new error or assign one of them to the overall error
overallError = configError ?: preferenceError;
}
// Now call the final completion block
completion(overallError);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment