1.监听已经存在的方法:
RACSignal *signal = [self rac_signalForSelector: @selector(viewWillAppear:)];
[signal subscribeNext:^(id _Nullable x) {
NSLog(@"监听到了");
}];
2.替换delegate:
方式一:使用rac_signalForSelector:fromProtocol:
//以下代码是在controller中
NewView *newView = [[NewView alloc] initWithFrame: CGRectMake(10, 10, 100, 110)];
[self.view addSubview: newView];
RACSignal *signal = [self rac_signalForSelector: @selector(protocolMethod) fromProtocol: @protocol(NewViewDelegate)];
[signal subscribeNext:^(id _Nullable x) {
NSLog(@"监听到了");
}];
//最后设置代理
newView.delegate = self;
方式二:使用RACSubject
//在添加delegate的.h文件中:
@interface NewView : UIView
@property (strong, nonatomic) RACSubject *subject;
@end
//.m文件中:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//代理回调的地方
if (self.subject) {
[self.subject sendNext: @"haha"];
}
}
//controller需要被回调的地方
NewView *newView = [[NewView alloc] initWithFrame: CGRectMake(10, 10, 100, 110)];
[self.view addSubview: newView];
newView.subject = [[RACSubject alloc] init];
[newView.subject subscribeNext:^(id _Nullable x) {
NSLog(@" ~~~ %@",x);
}];
3.替换监听、KVO
监听UITextField输入事件:
[[self.uidTF rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
NSLog(@"%@",x);
}];
替换系统kvo方式1:
[RACObserve(self.uidTF, text) subscribeNext:^(id _Nullable x) {
NSLog(@"observe :%@",x);
}];
替换系统kvo方式2:
//需要导入头文件 #import <ReactiveObjC/NSObject+RACKVOWrapper.h>
[self.view rac_observeKeyPath: @"frame"
options: NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew
observer: self
block:^(id value, NSDictionary *change, BOOL causedByDealloc, BOOL affectedOnlyLastComponent) {
}];
4.替换UIButton事件
UIButton *btn = [UIButton new];
[[btn rac_signalForControlEvents: UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
}];
5.替换通知NSNotification
[[[NSNotificationCenter defaultCenter] rac_addObserverForName: UIKeyboardDidHideNotification object: nil] subscribeNext:^(NSNotification * _Nullable x) {
}];
6.替换定时器
__block NSInteger i = 10;
self.timerDisposable = [[RACSignal interval: 1 onScheduler: [RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
i --;
if (i <= 0) {
[self.timerDisposable dispose];
}
}];