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

标签 afnetworking chaining reactive-programming reactive-cocoa

我正在探索 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/

相关文章:

ios - 使用 AFNetworking 下载时泄漏

ios - 我怎样才能在我的 UIImageView 上实现这种效果(圆角、内发光)?

swift - RxSwift - 如何在可观察值发生变化但仅发出最后一个值时重试?

android - 在 RxJava2 中将 Listener 转换为 Single

javascript - 延迟 n 秒重试轮询服务

macos - 无法使用 AFNetworkReachabilityManager 类在我的 OS X 项目中获取网络可达性

ios - 在afnetworking post方法中发送数组值

javascript - 是否有一种首选的方式来格式化 jQuery 链以使其更具可读性?

用于链接和释放的 C 矩阵函数设计

c# - C#继承和链接问题