Question

I have several asynchronous calls which I would combine in one call:

-(void) loadA:(ArrayBlock)completion failure(FailureBlock):failure;
-(void) loadB:(ArrayBlock)completion failure(FailureBlock):failure;
-(void) loadC:(ArrayBlock)completion failure(FailureBlock):failure;

The combined method, which uses the calls above:

- (void) loadAll:(ObjectBlock)completion;

The completion block contains an object with three arrays called array[A-C]. If any of the child calls fail the respective array in the object is simply set to nil.

Instead of nesting those three blocks and calling the next one on failure or completion of the preceding (This gets really messy) - I want to do something like the following using GCD:

  1. Add all calls to queue
  2. Wait until all calls have finished (either success or failure block was called)
  3. Combine all the results from the completion blocks and call the completion block of the loadAll method.

I know this is possible in GCD with synchronous calls but I don't see how to achieve this with my three asynchronous "child calls".

Was it helpful?

Solution

Read up on dispatch groups - you can do a synchronous wait on them. And really, messy is the wrong word - a bit complex might be stating it better. I've had great luck with nested dispatch blocks and using groups to wait for intermediate results. You can also use dispatch_async_barrier to prevent blocks already in the queue to finish before that block gets executed. Blocks can add blocks to their dispatch queue too!

I recall there being dependencies but I can't find that section now in the CGD literature.

What I really suggest you do is sketch this out on a piece of paper with a pencil, and once you convince your self you know how its going to work start coding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top