Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine signals in ReactiveCocoa to a new one that fires when all change

I'm trying to learn ReactiveCocoa and I'm writing a simple Space Invaders clone, based on a Ray Wenderlich tutorial. Lately during the development, I faced an issue I can't resolve. Basically I've two signals:

  • a tap gesture signal
  • a timed sequence that fires every second

What I want to achieve is to combine these signals in a new one, that fires when both the signals change: is it possible? I saw the combineLatest method, but the block is execute whenever any signals change.

My wanted pseudocode is:

RACSignal *updateEventSignal = [RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]];
RACSignal *gestureSignal = [[UITapGestureRecognizer new] rac_gestureSignal];
[[RACSignal combineBoth:@[gestureSignal, updateEventSignal]
                   reduce:^id(id tap, id counter){
                       return tap;
                   }]
 subscribeNext:^(id x) {
     NSLog(@"Tapped [%@]", x);
 }];

Probably I can achieve the same result in other way or this is not the expected behaviour or ReactiveCocoa, but at this point I wonder if I'm in the right reactive track or not.

like image 857
Giordano Scalzo Avatar asked Nov 22 '13 12:11

Giordano Scalzo


3 Answers

Instead of +combineLatest:reduce:, you want +zip:reduce:. Zip requires that all the signals change before reducing and sending a new value.

like image 169
Josh Abernathy Avatar answered Oct 05 '22 10:10

Josh Abernathy


Since you don't actually care about the values from the timer, -sample: may do what you want:

[[gestureSignal
    sample:updateEventSignal]
    subscribeNext:^(id tap) {
        NSLog(@"Tapped [%@]", tap);
    }];

This will forward the latest value from gestureSignal whenever updateEventSignal fires.

like image 37
Justin Spahr-Summers Avatar answered Oct 05 '22 10:10

Justin Spahr-Summers


   [[[[RACSignal zip:@[RACObserve(self, minimum), RACObserve(self, maximum), 
RACObserve(self, average)]] skip:1] reduceEach:^id{
            return nil;
        }] subscribeNext:^(id x) {
            [self buildView]; //called once, while all three values were changed.
        }];
like image 34
Naloiko Eugene Avatar answered Oct 05 '22 10:10

Naloiko Eugene