如何使用Reactive Cocoa和通知
如何从通知名称中创build一个信号? 例如,我想从:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidChange:) name:kTTCurrentUserLoggedOffNotification object:nil];
像这样的东西:
[signalForName(kTTCurrentUserLoggedOffNotification) subscribeNext:^(id x){ ... }];
-[NSNotificationCenter rac_addObserverForName:object:]
返回一个无限信号。 你可以这样订阅
Objective-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") }
这个信号是无限的。 如果你需要这个信号/订阅绑定到自己的生命周期,你可以添加takeUntil:
与rac_willDeallocSignal
是这样的:
Objective-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") }
在RACExtensions中,您可以findNSNotificationCenter (RACSupport)
类别。 这有一个方法来达到这个目的:
- (RACSignal *)rac_addObserverForName:(NSString *)notificationName object:(id)object;
使用ReactiveCocoa 4.1
Swift
版本:
NSNotificationCenter.defaultCenter() .rac_addObserverForName(UIKeyboardWillShowNotification, object: nil) .takeUntil(self.rac_willDeallocSignal()) .subscribeNext { (_) in print("UIKeyboardWillShowNotification") }