在下一个事件被消耗之前,如何在flattenMap块中等待信号完成?

时间:2014-03-10 11:11:53

标签: ios reactive-cocoa

这是我的伪代码:

[[[@[ctx1,ctx2]rac_sequence]signalWithScheduler:RACScheduler.immediateScheduler]

flattenMap:^RACStream *(id ctx) 
{
    // first flatten map
    return [RACSignal createSignal:^(id <RACSubscriber> subscriber) 
    {
        [executeRequestAsynch 
             onDone:^{
             [subscriber sendNext:ctx];  
             [subscriber sendCompleted]; 
    }
    ]

    }]
    flattenMap:^RACStream *(id ctx) {

    // second flattenMap  
    }];

}

现在这是订阅时我想要发生的事情:

1)  ctx1 should get fed to the first flattenMap block
2)  the Server Request "executeRequestAsynch" should be called
3)  on completion of the serverRequest the second flattenMap should be called with ctx1
4)  ctx2 should get fed to the first flattenMap block
5)  the Server Request "executeRequestAsynch" should be called
6)  on completion of the serverRequest the second flattenMap should be called with ctx1

但是这种情况发生了:

1)  ctx1 gets fed to the first flattenMap block
2)  the Server Request "executeRequestAsynch" is called
3)  ctx2 gets fed to the first flattenMap block
4)  the Server Request "executeRequestAsynch" is called
5)   on completion of the serverRequest the second flattenMap is called with ctx1
6)  on completion of the serverRequest the second flattenMap is called with ctx2

如何让第一个场景发生?


回答这似乎做了工作!谢谢: 输出是:

 Step 1
   Step 1 child
     Step 1    child child
 Step 2
   Step 2 child
     Step 2    child child
 done all

我仍然想知道在下面的Senario中会有什么延迟

-(RACSignal*) executeRequestAsynch:(NSString*) ctx {
 return [RACSignal createSignal:^RACDisposable * (id<RACSubscriber> subscriber) {
     NSLog(@"  %@ child",ctx);
     [subscriber sendCompleted];
                 return nil;
        }];

}

-(RACSignal*) executeRequestAsynch2:(NSString*) ctx {
return [RACSignal createSignal:^RACDisposable * (id<RACSubscriber> subscriber) {
    NSLog(@"  %@    child child",ctx);
    [subscriber sendCompleted];
    return nil;
}];

 }

  - (void)viewDidLoad
{
    [super viewDidLoad];
    RACSignal *contexts = [[@[ @"Step 1", @"Step 2" ] 
    rac_sequence]  signalWithScheduler:RACScheduler.immediateScheduler];
    RACSignal *ne = [[contexts map:^(id ctx) {
    NSLog(@"%@",ctx);
    return [[self executeRequestAsynch:ctx] concat: [self executeRequestAsynch2:ctx ]];}]concat] ;
   [ne subscribeCompleted:^{
    NSLog(@"done all");
}];
}

here is my final real solution

1 个答案:

答案 0 :(得分:1)

我不是百分百肯定我理解你想要完成的事情。我的解释是这样的:

RACSignal *contexts = [@[ ctx1, ctx2 ] things.rac_sequence signalWithScheduler:RACScheduler.immediateScheduler];
[[contexts map:^(id ctx) {
    return [executeRequestAsynch concat:[RACSignal defer:^{
        // Returns another signal involving ctx?
    }]];
}] concat];

这将每个上下文映射到executeRequestAsynch,然后将它们连接起来,以便它们按顺序完成。

这是对的还是我误解了你?