swiftreactive-cocoaracsignal

How to create a looping RACSignal with RACScheduler


Is there a way to create a scheduled RACSignal that emits value every interval of time ?

I'm wondering if there is a way other than creating a dispatch timer ? or some kind of for loop.


Solution

  • There is! I think you're looking for interval:onScheduler:. It will emit the current NSDate, which is usually not that useful, so you can use it to sample another signal that has the data you want. For example, with a constant value:

    [[RACSignal return:@20] sample:[RACSignal interval:1.0
                                           onScheduler:[RACScheduler mainThreadScheduler]]];
    

    Edit:

    ...or you could just mapReplace that...

    [[RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]] mapReplace:@20];
    

    If you want to perform a calculation every time the interval ticks, and you don't have that as another signal, you can use a normal map that ignores its argument.

    [[RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]] map:^(id x) {
        return ...
    }];