【问题标题】:Combine Multiple Network Requests with ReactiveCocoa使用 ReactiveCocoa 组合多个网络请求
【发布时间】:2013-06-07 11:14:14
【问题描述】:

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

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

我正在使用 AFNetworking 的 RACEExtensions 来发出请求。代码如下所示:

- (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 chaining reactive-programming reactive-cocoa


【解决方案1】:

我不得不研究 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 仅返回返回对象中的 RACStreamAFURLConnectionOperation+RACSupport.m 应使用类型信息改进头文件中的文档以理顺这一点。

不过,代码不错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    相关资源
    最近更新 更多