如何等待RACSequence完成它的任务

时间:2015-09-22 16:36:27

标签: ios reactive-cocoa

示例我需要完成2个任务:

任务1:将数组中的所有产品保存到数据库中。 任务2:从DB获取产品。

问题:当任务1尚未完成时,任务2正在运行。所以我希望任务1完成,然后任务2将在那之后运行

这是我的代码:

RACSignal *productsSignal = [[[[products rac_sequence] signalWithScheduler:

[RACScheduler currentScheduler]] flattenMap:^RACStream *(JMProduct *product) {

            return [self.storage saveProduct:product] ;

        }] then:^RACSignal *{
            return [self.storage getProductsFromLocalForModule:moduleId];
        }];

我在上面的代码中出错了什么? 如果我的英语不好,感谢您的回答和抱歉

1 个答案:

答案 0 :(得分:1)

我认为你需要的是concat操作。您可以将信号流连接成一个信号,该信号将在所有连接信号发送完成时完成。

在您的示例中,您有几个要等待先完成的保存操作(连续结果),然后执行加载操作。

我会用RAC 2.x

这样说
[[[RACSignal concat:

   // concat the results of save operations
   // concat will complete when all the save signals complete

   [@[@"product1", @"product2", @"product3"].rac_sequence
        map:^RACStream *(NSString* product) {
            NSLog(@"Save product: %@", product);

            // do sync / async save operations and which send complete when finished
            return [RACSignal return:@"Save product operation complete"];
        }]

] then:^RACSignal *{
    NSLog(@"Load products");

    // do sync / async load operation which sends complete when finished
    return [RACSignal return:@"Load product operation complete"];
}] subscribeNext:^(id x) {
    NSLog(@"Save and load finished");
}];

确保在某些时候完成连接的保存信号。