Reactive Cocoa:仅订阅新值

时间:2022-03-30 21:37:46

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:

我是Reactive Cocoa的新手。我想要实现的是每次财产价值变化时都会收到通知。但是,当属性设置为相同值时,我不希望收到通知。这是一些代码:

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?

我预计“改变了”只打印一次,而不是五次。有没有办法只订阅新值?

1 个解决方案

#1


There is a method for that, distinctUntilChanged:

有一种方法,distinctUntilChanged:

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

#1


There is a method for that, distinctUntilChanged:

有一种方法,distinctUntilChanged:

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