iOS - Concatenating asynchronous block-based opera

2019-09-14 03:57发布

问题:

How would you perform N asynchronous operations, such as network calls, working with completion block operations and no delegates/notifications?

Given N methods like this:

- (void)methodNWithCompletion:(void (^)(Result *))completion {
    Operation *operation = [Operation new];

    // ...
    // Asynchronous operation performed here
    // ...

    return;
}

A straightforward solution would be to call each operation in the completion block of the previous one:

[self method1WithCompletion:^(Result *result) {
    // ...
    [self method2WithCompletion:^(Result *result) {
        // ...
        [self method3WithCompletion:^(Result *result) {
            // ...
            [self method4WithCompletion:^(Result *result) {
                NSLog(@"All done");
            }
        }
    }
}

but I'm looking for a more elegant and reusable solution, easier to write and maintain (with no many indented blocks).

Many thanks, DAN

回答1:

It all depends on what you want to do. Many powerful sophisticated tools are at your disposal. You can use such things as:

  • Serial queue (if you want the completion blocks run in order)

  • Concurrent queue (if you don't care whether the completion blocks execute simultaneously or in what order)

  • Dispatch group (if there is something you want to do only after all completion blocks have finished)

  • Operation and OperationQueue (if you want to establish the dependency order in which networking operations must take place - see esp. the fantastic WWDC 2015 video on this topic)