gpt4 book ai didi

afnetworking - 使用 ReactiveCocoa 组合多个网络请求

转载 作者:行者123 更新时间:2023-12-04 04:08:48 25 4
gpt4 key购买 nike

我正在探索 ReactiveCocoa 并试图看看有什么可能。我遇到的问题是将几个网络请求链接在一起。

我有 2 个调用,第一个获取标识符列表,然后针对每个标识符调用以获取与该 ID 对应的数据并创建一个模型对象并返回一个对象数组。

我正在使用 AFNetworking 的 RACExtensions 来发出请求。代码看起来像这样:

- (RACSignal *) identifersInfo
{
return [[[[self identifiersSignal] flattenMap:^RACStream *(RACTuple *tuple) {
RACTupleUnpack(AFHTTPRequestOperation *operation, id responseObject) = tuple;
NSArray *identifiers = responseObject[@"Identifiers"];
NSArray *requests = [self httpRequestsWithIdentifiers: identifiers];
return [self.client rac_enqueueBatchOfHTTPRequestOperationsWithRequests: requests];
}] collect] map:^id(RACTuple *tuple) {
RACTupleUnpack(AFHTTPRequestOperation *operation, id responseObject) = tuple;
Model *model = [[Model alloc] init];
model.title = responseObject[@"Title"];
model.description = responseObject[@"Description"];
model.lastUpdated = responseObject[@"LastUpdated"];
return model;
}];
}

identifiersSignal 方法如下所示:

- (RACSignal *) identifiersSignal
{
return [self.client rac_getPath: @"identifiers" parameters: nil];
}

这将返回 json 字典,如下所示:

{
"Identifiers": [
3,
4,
21
]
}

我现在实际上是在模拟这些调用,我知道它们是独立工作的,我只是想用 ReacticeCocoa 将它们拼凑起来。

我无法弄清楚或找到任何关于如何使用 ReactiveCocoa 实现这一点的像样的示例,尽管我非常有信心它可以做到。

最佳答案

我不得不研究 AFNetworking 扩展的实现,但我认为您滥用了一些返回值。我没有测试过,但看起来你的代码应该是这样的:

- (RACSignal *) identifersInfo {
return [[[self identifiersSignal] map:^RACSignal *(RACTuple *tuple) {
RACTupleUnpack(AFHTTPRequestOperation *operation, id responseObject) = tuple;
NSArray *identifiers = responseObject[@"Identifiers"];
NSArray *requests = [self httpRequestsWithIdentifiers: identifiers];
return [self.client rac_enqueueBatchOfHTTPRequestOperationsWithRequests: requests];
}] map:^Model*(id *reponseObject) {
Model *model = [[Model alloc] init];
// same as above
return model;
}];
}

rac_getPath 返回一个 RACTuple 有点误导,因为 rac_enqueueBatchOfHTTPRequestOperationsWithRequests 只返回一个 RACStream对象。 AFURLConnectionOperation+RACSupport.m应使用类型信息改进头文件中的文档,以理清这一点。

虽然代码不错。

关于afnetworking - 使用 ReactiveCocoa 组合多个网络请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16982763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com