对数组中的每个项进行串行异步调用

时间:2014-10-13 22:50:33

标签: objective-c reactive-cocoa

给定一个对象数组,我想对每个对象进行异步调用,然后在前一个对象的异步调用完成之前不进行下一个对象。

我有这个工作代码:

#import <XCTest/XCTest.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
#import <TRVSMonitor/TRVSMonitor.h>

@interface FSReactiveCocoaArraySignalProcessingTests : XCTestCase{
    NSArray *sequence;
}
@end

@implementation FSReactiveCocoaArraySignalProcessingTests

-(void)setUp{
    [super setUp];
    sequence = @[@"dog", @"cat", @"mouse", @"rabbit", @"wallabee"];
}

-(void)tearDown{
    [super tearDown];
}

- (void)test_maybe_using_the_disposable_method_of_creating_a_signal{
    TRVSMonitor *monitor = [TRVSMonitor monitor];
    RACSignal *resultingSignal = [[sequence.rac_sequence
                                   map:^(NSString *val){
                                       return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                                           NSLog(@"returning signal for %@", val);
                                           [[self fakeApiCall:val]
                                            subscribeNext:^(id next){
                                                [subscriber sendNext:next];
                                            }
                                            completed:^{
                                                [subscriber sendCompleted];
                                            }];
                                           return nil;
                                       }];
                                   }]
                                  foldLeftWithStart:[RACSignal empty]
                                  reduce:^RACSignal *(RACSignal *left, RACSignal *right){
                                      return [left
                                              then:^{
                                                  return [right doNext:^(RACTuple *tuple){
                                                      //real world side effect for processing end of call.
                                                      RACTupleUnpack(NSString *val, NSNumber *len) = tuple;
                                                      NSLog(@"word %@ has %@ chars", val, len);
                                                  }];
                                              }];
                                  }];

    [resultingSignal subscribeCompleted:^{
         NSLog(@"FIN!");
         [monitor signal];
     }];

    XCTAssertTrue([monitor waitWithTimeout:10]);
}

//Returns a new signal that returns a RACTuple<NSString *, NSNumber *>
-(RACSignal *)fakeApiCall:(NSString *)val{
    return [[RACSignal return:RACTuplePack(val, @(val.length))]
      delay:.5];
}
@end

https://gist.github.com/jonnolen/b0e071b8dd202f7ed912

问题:是否有“更具反应性”的方法来实现这一目标?

0 个答案:

没有答案