【问题标题】:Moya - chain requests with NSOperationMoya - 使用 NSOperation 链式请求
【发布时间】:2018-06-19 14:47:17
【问题描述】:
我有几个需要链接的请求。我可以这样做
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 链接它们。
我该怎么做?
【问题讨论】:
标签:
swift
nsoperationqueue
nsoperation
moya
【解决方案1】:
我是 Swift 的初学者,但通过代码我了解到您正在请求“苹果”。如果该请求成功,则再次请求“Oranges”,如果成功,则请求其他水果,依此类推。
是的,您可以使用 NSOperation 链接它们,请参阅我对以下问题的回答,我在其中概述了 2 种不同的方法。
Do NSOperations and their completionBlocks run concurrently?
注意:这里有几种情况:
1)只有“apples”请求成功才需要请求“oranges”,只有“oranges:请求成功”才请求其他水果?
在这种情况下,您可以参考上述问题中的答案。示例流程如下:
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) 如果你可以同时请求“apples”、“oranges”和“other fruits”,而无需等待彼此成功,那么你不需要将它们链接起来。您可以将操作添加到队列中。
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];