Search code examples
ioscocoareactive-cocoa

Reactive Cocoa: subscribe only to new values


I'm new to Reactive Cocoa. What I'm trying to achieve is get notified every time property value changes. However, I don't want to get notified when property is set to the same value. Here's some code:

self.testProperty = 0;
[[RACObserve(self, self.testProperty) skip:1] subscribeNext:^(id x) {
    NSLog(@"Did Change: %@", x);
}];

self.testProperty = 1;
self.testProperty = 1;
self.testProperty = 1;
self.testProperty = 1;
self.testProperty = 1;

And this is what I get on console's output

> Did Change: 1
> Did Change: 1
> Did Change: 1
> Did Change: 1
> Did Change: 1

I expected that "Did change" would be printed only once, not five. Is there any way to subscribe only to new values?


Solution

  • There is a method for that, distinctUntilChanged:

    [[[RACObserve(self, self.testProperty) 
      skip:1]
      distinctUntilChanged]
      subscribeNext:^(id x) {
        NSLog(@"Did Change: %@", x);
    }];