如何使用Reactive Cocoa和通知

mei*_*sel 19 ios reactive-cocoa

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

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(userDidChange:)
                                             name:kTTCurrentUserLoggedOffNotification
                                           object:nil];
Run Code Online (Sandbox Code Playgroud)

类似于:

[signalForName(kTTCurrentUserLoggedOffNotification) subscribeNext:^(id x){
...
}];
Run Code Online (Sandbox Code Playgroud)

hfo*_*sli 46

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

Objective-C的

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

迅速

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

该信号如无限所述.如果您需要此信号/订阅绑定到寿命self,您可以添加takeUntil:使用rac_willDeallocSignal这样的:

Objective-C的

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

迅速

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

  • @allprog [订阅者保留他们的信号](https://github.com/ReactiveCocoa/ReactiveCocoa/blob/master/Documentation/MemoryManagement.md),直到完成,错误或处置.这就是无限信号变得非常粗糙的原因.`-takeUntil:`是一个很好的解决方案,或类似的东西,确定性地终止某一点的信号. (4认同)
  • @ JustinSpahr-Summers感谢您的澄清.我知道我太急于喊狼了!但你在那里纠正我.:)文档可能包含这些错综复杂的内容吗?例如"这是一个无限的信号",并给出一些指示,指示一个人需要考虑的内容.我会说实话,框架似乎有一些"诱杀陷阱",如果强调这些情况下返回信号的细节会更好. (2认同)

all*_*rog 10

RACExtensions中,您可以找到该NSNotificationCenter (RACSupport)类别.这有一个方法:

- (RACSignal *)rac_addObserverForName:(NSString *)notificationName
                               object:(id)object;
Run Code Online (Sandbox Code Playgroud)

  • 发现:)看到新的答案 (2认同)