Moya-使用NSOperation的链请求

时间:2018-06-19 14:47:18

标签: swift nsoperationqueue nsoperation moya

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

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链接它们。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我是Swift的初学者,但仔细阅读代码后,我知道您正在请求“苹果”。如果该请求成功,则再次请求“ Oranges”,如果成功,则请求其他水果,依此类推。

是的,您可以使用NSOperation链接它们,请参考以下问题的答案,其中概述了2种不同的方法。

Do NSOperations and their completionBlocks run concurrently?

注意:这里有几种情况: 1)仅在“苹果”请求成功后才需要请求“橙色”,而仅在“橙色:请求成功”时才请求其他水果吗? 在这种情况下,您可以参考上述问题的答案。示例流程如下:

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)如果您可以并行请求“苹果”,“橙子”和“其他水果”,而不必等待彼此成功,则不需要将它们链接在一起。您只需将操作添加到队列中即可。

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];