Scenario 1:
Reads from the data source to n values, and then needs to traverse these n values to initiate an HTTP request separately. After processing is complete, call a final summary method
This scenario can easily be achieved if you use the JS Async framework:
Async.series ([Task1, Task2, Task3], function (err) { //Summary code}); function Task1 (callback) { //HTTP request callback (null);} function Task2 (callback) { ///HTTP request callback (NULL);} function Task3 (callback) { ///HTTP request callback (NULL);}
But in iOS, it's more troublesome, and finally it's implemented with Dispatch_group:
dispatch_group_t group = Dispatch_group_create (); while ([Rs next]) { dispatch_group_enter (group); [SyncService Refreshmemberswithenterpriseid:enterpriseid latestsynctime:latestsyncdate Block:^ (BOOL flag) { dispatch_group_leave (group); }];} Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{ //Summary Code});
Scenario 2:
Then the demand changed and the scene was a little more complicated. For each value, multiple HTTP requests are initiated (scenario 1 requires only 1 requests). After all requests are finished, call the Rollup method
So at first I wrote something like this:
dispatch_group_t group = Dispatch_group_create (); while ([Rs next]) { dispatch_group_enter (group); dispatch_group_t Group_inner = Dispatch_group_create (); Dispatch_group_enter (Group_inner); [SyncService Refreshmemberswithenterpriseid:enterpriseid latestsynctime:latestsyncdate Block:^ (BOOL flag) { dispatch_group_leave (group_inner); }]; Dispatch_group_enter (Group_inner); [SyncService Refreshreportswithenterpriseid:enterpriseid latestsynctime:latestsyncdate Block:^ (BOOL flag) { dispatch_group_leave (group_inner); }]; Dispatch_group_notify (Group_inner, dispatch_get_global_queue (0, 0), ^{ dispatch_group_leave (group); }); Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{ //Summary Code});
After the completion of the discovery, in fact, in this scenario, do not need to nest group, sharing a group is no problem
dispatch_group_t group = Dispatch_group_create (); while ([Rs next]) { dispatch_group_enter (group); [SyncService Refreshmemberswithenterpriseid:enterpriseid latestsynctime:contactlatestsync Block:^ (BOOL flag) { dispatch_group_leave (group); }]; Dispatch_group_enter (group); [SyncService Refreshreportswithenterpriseid:enterpriseid latestsynctime:reportlatestsync Block:^ (BOOL flag) { dispatch_group_leave (group); }];} Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{ //Summary Code});
Because there is no need for a rollup for each group, it is necessary to nest groups if each group has its own summary logic to perform.