ReactiveCocoa 和 NSThread 操场

ReactiveCocoa and NSThread playground

我找到了一些代码,但我不太明白它是如何工作的:

RACSignal *oneNumberEverySecond = [[RACSignal
                                    interval:1.0f
                                    onScheduler:[RACScheduler scheduler]]
                                   scanWithStart:@0 reduce:^id(NSNumber *running, NSDate *next) {
                                       return @(running.unsignedIntegerValue + 1);
                                   }];
[oneNumberEverySecond subscribeNext:^(id x) {
     NSLog(@"%@", x);
 }];

[NSThread sleepForTimeInterval:5.0f];

当我注释掉 [NSThread sleepForTimeInterval:5.0f] 时,信号停止发送值。为什么?

原因是 onScheduler:[RACScheduler scheduler] 在后台线程上发出此信号 运行。这意味着只有当它的线程是 OS 的 运行 时它才会工作。当您调用 [NSThread sleepForTimeInterval: 5.0f] 时它看起来像工作的原因是因为这将阻塞在给定时间内调用它的任何线程。在你的情况下,它将阻塞主线程,这将允许 OS 给你的背景信号时间来触发。如果你注释掉 [NSThread sleepForTimeINterval: 5.0f]; 你会发现它仍然有效,但我很可怜,并不总是火。