3

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

user3620372
  • 187
  • 1
  • 9

1 Answers1

3

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");
 }];
Patrick Bacon
  • 343
  • 1
  • 9
Michał Ciuba
  • 7,876
  • 2
  • 33
  • 59
  • Thanks, I had the same problem, and your answer works. I don't understand why it doesn't work with 'then'. In the github example of chaining operations, it uses both 'flattenMap' and 'then'. Thank you if you can enlighten me ;) – darksider Feb 27 '15 at 09:12
  • `then` executes the second signal after the first one completes, `flattenMap`- after the first signal sends next. The'timer' signal never completes, it only sends next values. – Michał Ciuba Feb 27 '15 at 09:16