首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Moya - chain requests with NSOperation

Moya - chain requests with NSOperation
EN

Stack Overflow用户
提问于 2018-06-19 22:47:18
回答 1查看 455关注 0票数 1

我有几个请求需要链接。我可以这样做

代码语言:javascript
复制
provider.request(.apples) { (result) in
        switch result {
        case .success(let response):

           provider.request(.oranges) { (result) in
                switch result {
                case .success(let response):

                   ...couple of other fruits

                case .failure(let error):
                  print(error)
        }
    }

        case .failure(let error):
            print(error)
        }
    }

但是我想用NSOperation链接它们。

我该怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2018-07-05 10:43:59

我是Swift的初学者,但通过代码我明白你是在请求“苹果”。如果该请求成功,则再次请求“Orange”,如果成功,则请求其他水果,依此类推。

是的,你可以使用NSOperation链接它们,请参考我对以下问题的回答,我已经列出了两种不同的方法。

Do NSOperations and their completionBlocks run concurrently?

注意:这里有几种场景: 1)是否只有苹果请求成功才需要请求橙子,只有在橙子:请求成功的情况下才需要请求其他水果,这种情况下可以参考上述问题的答案。示例流程如下:

代码语言:javascript
复制
RequestFruitOperation *requestApplesOperation = [[RequestFruitOperation alloc] initWithFruitType:Apples];

[requestApplesOperation setCompletionBlock:^{
    if(requestApplesOperation.success){
        //add oranges
        RequestFruitOperation *requestOrangesOperation = [[RequestFruitOperation alloc] initWithFruitType:Oranges];
        [requestOrangesOperation setCompletionBlock:^{
            if(requestOrangesOperation.success) {
                //add mangoes
                RequestFruitOperation *requestMangosOperation = [[RequestFruitOperation alloc] initWithFruitType:Mangos];
                [operationQueue addOperation:requestMangosOperation];
            }
        }];
        [operationQueue addOperation:requestOrangesOperation];
    }

}
 [operationQueue addOperation:requestApplesOperation];

2)如果你可以并行请求“苹果”,“橙子”和“其他水果”,而不是等待对方成功,那么你就不需要链接它们。您可以只将操作添加到队列中。

代码语言:javascript
复制
RequestFruitOperation *requestApplesOperation = [[RequestFruitOperation alloc] initWithFruitType:Apples];
[operationQueue addOperation:requestApplesOperation];

RequestFruitOperation *requestOrangesOperation = [[RequestFruitOperation alloc] Oranges];
[operationQueue addOperation:requestOrangesOperation];

RequestFruitOperation *requestMangosOperation = [[RequestFruitOperation alloc] Mangos];
[operationQueue addOperation:requestMangosOperation];
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50931239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档