使用Dispatch Groups来管理多个Web Services请求

原文:Using Dispatch Groups to Wait for Multiple Web Services

假设你的应用在启动时必须向服务端进行一连串的请求.这些请求可能是获取配置信息.举个例子,当你的应用启动时可能会向服务端请求一些配置信息.这个配置信息可能需要多个请求组合而成.

你想通过调用一个方法去启动这些请求,然后全部请求完成后,在一个completion block里面完成你的业务逻辑.但是这些请求相互间没有什么联系,我们应该如何做呢?

在你看到你的代码像下面的这个样子时,可能你需要重构你的代码.

               }];
            }];
        }];
    }];
}];

初始化一个dispatch group

很简单:

dispatch_group_t serviceGroup = dispatch_group_create();

向dispatch group中添加任务

有两种方法,第一种是在这个dispatch group中添加你的代码块,然后这些代码块会运行在你指定的queue中.

dispatch_group_async(serviceGroup,queue,^{
    // some work here
});

这不是我们想要的,请求web服务我们需要的是可以马上返回,然后每个请求中都有自己的completion block.这样,dispatch group会认为我们的请求是'马上完成'的.

第二种方法是手动告诉dispatch group你要开始某个任务了.完成任务之后,你也需要手动退出dispath group.

通过dispatch_group_enter(),dispatch_group_leave()两个方法可以实现进入,退出两个动作:

dispatch_group_enter(serviceGroup);
[configService startWithCompletion:^(ConfigResponse *results, NSError* error){
    // Do something with the error or results
    dispatch_group_leave(serviceGroup);
}];

每个enter都必须有相应的leave,否则,你的dispatch group永远不会结束.在你要去请求一个web service的时候,你先enter dispatch group,然后在返回的completion block中 leave.

dispatch group完成方式

有两种方式.

第一种是阻塞当前的线程,直到dispatch group中的所有任务完成才会返回.

dispatch_group_wait(serviceGroup,DISPATCH_TIME_FOREVER);
// Won't get here until everything has finished

第二种不会阻塞当前线程,马上返回.

dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
    // Won't get here until everything has finished
});

在这里我们会使用第二种方法.

Putting it all together

下面我们来实现请求多个web service的方法:

-(void)fetchConfigurationWithCompletion:(void (^)(NSError* error))completion
{
    // Define errors to be processed when everything is complete.
    // One error per service; in this example we'll have two 
    __block NSError *configError = nil;
    __block NSError *preferenceError = nil;

    // Create the dispatch group
    dispatch_group_t serviceGroup = dispatch_group_create();

    // Start the first service
    dispatch_group_enter(serviceGroup);
    [self.configService startWithCompletion:^(ConfigResponse *results, NSError* error){
        // Do something with the results
        configError = error;
        dispatch_group_leave(serviceGroup);
    }];

    // Start the second service
    dispatch_group_enter(serviceGroup);
    [self.preferenceService startWithCompletion:^(PreferenceResponse *results, NSError* error){
        // Do something with the results
        preferenceError = error;
        dispatch_group_leave(serviceGroup);
    }];

    dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
        // Assess any errors
        NSError *overallError = nil;
        if (configError || preferenceError)
        {
            // Either make a new error or assign one of them to the overall error
            overallError = configError ?: preferenceError;
        }
        // Now call the final completion block
        completion(overallError);
    });
}

你可以跟踪每个请求的完成结果,然后做出相应的动作.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Managing Units of Work(管理工作单位) 调度块允许您直接配置队列中各个工作单元的属性。它们还...
    edison0428阅读 8,073评论 0 1
  • 为什么使用并发组请求? 在实际开发中我们通常会遇到这样一种需求:某个页面加载时通过网络请求获得相应的数据,再做某些...
    fruitymoon阅读 4,366评论 16 66
  • 1 GCD 术语 1.1 Serial vs. Concurrent 串行 vs. 并发 概念:该术语描述执行当前...
    NinthDay阅读 3,984评论 2 38
  • 接受 播下一颗种子,不用去期待什么结果,让缘分下去,自然下去,期盼一个说不定,接受一个无结果
    赵霞1阅读 115评论 0 0
  • 别人伤害你的时候从不会考虑到你的感受,处境,就像蚊子盯你的时候并不会思索要刺痛你的哪一寸肌肤,只会伺机而动,稳准狠...
    崽崽么么哒阅读 377评论 0 0