1

What are the best practices in dealing with multiple asynchronous web calls.

Senario:

I'm grabbing a large list of addresses from a JSON feed from one web service, also querying CLGeocoder for a lat/long lookup from an address string. Then once I have both pieces of info I want to perform an action.

Whats the best way of doing this with out coupling all the methods together in a linked chain?

Matt Price
  • 34,499
  • 6
  • 24
  • 33
  • That's tricky problem. I'll recommend just starting off the first async and when it's finished start the second one and when the second is finished perform your action. – Devfly Mar 16 '13 at 18:31

2 Answers2

7

Wait for synchronous tasks:

I'd recommend creating a new NSOperationQueue, configure it to have as many threads as you need and then you launch your operations on that thread. To wait for them to complete, simply call waitUntilAllOperationsAreFinished method.

For example:

NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];

// Add your tasks here

[operationQueue addOperationWithBlock:^{
    // Long running task
}];

[operationQueue waitUntilAllOperationsAreFinished];

Be careful to not block the main thread or your Application will become unresponsive while it loads.

If you need something more complex than this, you can use the lower level API dispatch_group_t to group threads and wait for them. Take a look at this response for a deeper explanation.

Wait for already asynchronous tasks:

Sometimes the methods described above are not enough, probably because you need to wait for an already asynchronous task (like enabling GPS or waiting for some external event). In these cases you can use a semaphore. You have to be very careful with error handling and semaphores, or you could block a thread forever.

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

[object performLongOperationAndDo:^{
    dispatch_semaphore_signal(sema);
}];

dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);

More info about Obj-C semaphores.

Unless necessary, I'd stick to NSOperationQueue.

Community
  • 1
  • 1
redent84
  • 18,901
  • 4
  • 62
  • 85
1

Maybe you'll find this useful: Reactive Cocoa

Its a really elegant solution for your type of problem. The framework has a really steep learning curve tough.

tsp
  • 1,938
  • 18
  • 15