19

如何从通知名称中创建信号?例如,我想从:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(userDidChange:)
                                             name:kTTCurrentUserLoggedOffNotification
                                           object:nil];

类似于:

[signalForName(kTTCurrentUserLoggedOffNotification) subscribeNext:^(id x){
...
}];
4

3 回答 3

46

-[NSNotificationCenter rac_addObserverForName:object:]返回一个无限信号。你可以像这样订阅它

目标-c

[[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil]
  takeUntil:[self rac_willDeallocSignal]]
  subscribeNext:^(id x) {
     NSLog(@"Notification received");
}];

迅速

NSNotificationCenter.defaultCenter()
  .rac_addObserverForName(UIKeyboardWillShowNotification, object: nil)
  .takeUntil(self.rac_willDeallocSignal())
  .subscribeNext { (_) in
     print("Notification received")
  }

该信号如上所述是无限的。如果您需要将此信号/订阅绑定到您的生命周期,可以self像这样添加:takeUntil:rac_willDeallocSignal

目标-c

[[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil]
  takeUntil:[self rac_willDeallocSignal]]
  subscribeNext:^(id x) {
     NSLog(@"Notification received");
}];

迅速

NSNotificationCenter.defaultCenter()
  .rac_addObserverForName(UIKeyboardWillShowNotification, object: nil)
  .takeUntil(self.rac_willDeallocSignal())
  .subscribeNext { (_) in
     print("Notification received")
  }
于 2013-11-14T15:51:39.673 回答
10

RACEExtensions 中,您可以找到该NSNotificationCenter (RACSupport)类别。有一个为此目的的方法:

- (RACSignal *)rac_addObserverForName:(NSString *)notificationName
                               object:(id)object;
于 2013-08-12T08:05:10.500 回答
-1

Swift版本使用ReactiveCocoa 4.1

NSNotificationCenter.defaultCenter()
      .rac_addObserverForName(UIKeyboardWillShowNotification, object: nil)
      .takeUntil(self.rac_willDeallocSignal())
      .subscribeNext { (_) in
          print("UIKeyboardWillShowNotification")
      }
于 2016-04-12T13:58:56.640 回答