iosreactive-programmingreactive-cocoaracsignal

ReactiveCocoa : Chain a signal with a repeating signal


Using ReactiveCocoa, how can I chain a signal from a repeating one?

I would like to do something like this: Every 5 seconds, I run a network request.

For this purpose, I created a repeating signal

RACSignal *each5SecondSignal = [[[RACSignal interval:5 onScheduler:[RACScheduler mainThreadScheduler]] take:1] concat:[RACSignal 5 onScheduler:[RACScheduler mainThreadScheduler]]];

and a signal for fetching data

RACSignal* iframeSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {....

But I don't know how to chain those. Here are my attempt (with the 'then' method).

//This doesn't work, the log do not appear
[[each5SecondSignal then:^RACSignal *{
   return iframeSignal;
 }] subscribeNext:^(id x) {
   NSLog(@"Request was made");
 }];

However, when I do [iframeSignal subscribeNext...] the content of the signal is called, and when I do

//OK is logged every 5 seconds
[each5SecondSignal subscribeNext:^(id x) {
    NSLog(@"OK");
  }];

the log appears as expected.

Could you help me?

Sincerely

Jery


Solution

  • First of all, the each5SecondSignal can be much simpler. You don't have to call take: as it will cause the signal to complete after 5 seconds, and if I understood you correctly you want the signal to go on forever.

    RACSignal *each5SecondSignal = [RACSignal interval:5 onScheduler:[RACScheduler mainThreadScheduler]]
    

    And you can use flattenMap: so that iframeSignal is called each time each5SecondSignal sends next value (which happens every 5 seconds):

    [[each5SecondSignal flattenMap:^RACStream *(id value) {
       return iframeSignal;
     }] subscribeNext:^(id x) {
       NSLog(@"Request was made");
     }];