如何使用Reactive Cocoa和通知 [英] How to use Reactive Cocoa with notifications

查看:154
本文介绍了如何使用Reactive Cocoa和通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I create a signal out of a notification name? For example, I want to go from:

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

类似于:

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


推荐答案

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

-[NSNotificationCenter rac_addObserverForName:object:] returns an infinite signal. You can subscribe to it like this

Objective-c

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

Swift

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






此信号如无限所述。如果您需要此信号/订阅绑定到 self 的生命周期,您可以使用<$ c添加 takeUntil: $ c> rac_willDeallocSignal 喜欢这样:


This signal is as stated infinite. If you need this signal/subscription to be bound to the lifetime of self you can add takeUntil: with rac_willDeallocSignal like this:

Objective-c

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

Swift

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

这篇关于如何使用Reactive Cocoa和通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆