Search code examples
iosobjective-creactive-programmingreactive-cocoa

ReactiveCocoa and NSThread playground


I found some code and I don't quite understand how it works:

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];

When I comment out [NSThread sleepForTimeInterval:5.0f] then signal stops sending values. Why?


Solution

  • The reason for this is that the onScheduler:[RACScheduler scheduler] makes this signal run on a background thread. This means means it will only do work if its thread is run by the OS. The reason it looks like its working when you call [NSThread sleepForTimeInterval: 5.0f] is because that will block whatever thread it is being called on for the given time. In your case it will block the main thread which will allow the OS to give your background signal time to fire. If you comment out [NSThread sleepForTimeINterval: 5.0f]; you will see that it still works but my be pathcy and not always fire.