How can I make an NSOperationQueue (or anything else) wait for two async network calls with callbacks? The flow needs to look like this
Block Begins {
Network call with call back/block begins {
first network call is done
}
}
Second Block Begins {
Network call with call back/block begins {
second network call is done
}
}
Only run this block once the NETWORK CALLS are done {
blah
}
Here's what I have so far.
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
__block NSString *var;
[queue addOperation:[NSBlockOperation blockOperationWithBlock:^{
[AsyncReq get:^{
code
} onError:^(NSError *error) {
code
}];
}]];
[queue addOperation:[NSBlockOperation blockOperationWithBlock:^{
[AsyncReq get:^{
code
} onError:^(NSError *error) {
code
}];
}]];
[queue waitUntilAllOperationsAreFinished];
//do something with both of the responses
Using Grand Central Dispatch and
DispatchGroup
With Swift 3, in the simplest cases where you don't need fine grained control on tasks states, you can use Grand Central Dispatch and
DispatchGroup
. The following Playground code shows how it works:The previous code will print
"Task Three finished"
once the two asynchronous tasks are both finished.Using
OperationQueue
andOperation
Using
OperationQueue
andOperation
for your request tasks requires more boilerplate code but offers many advantages likekvo
ed state and dependency.1. Create an
Operation
subclass that will act as an abstract class2. Create your operations
3. Usage
With this code,
operation3
is guaranteed to always be performed last.You can find this Playground on this GitHub repo.
Do you have to use
NSOperation Queue
? Here's how you can do it w/ a dispatch group:AsyncOperation maintains its state w.r.t to Operation own state. Since the operations are of asynchronous nature. We need to explicitly define the state of our operation. Because the execution of async operation returns immediately after it's called. So in your subclass of AsyncOperation you just have to set the state of the operation as finished in your completion handler
Now to call if from your own Operation class