ReactiveObjC(OC版ReactiveCocoa)的安装与使用
https://github.com/ReactiveCocoa/ReactiveObjC/blob/master/README.md#when-to-use-reactiveobjc
http://blog.csdn.net/mazy_ma/article/details/68508090
https://www.cnblogs.com/qq9070/p/6795502.html
一、使用pod导入第三方库ReactiveCocoa
podfile文件内容如下:
platform :ios,'8.0' target 'MyReactiveCocoa' do use_frameworks! pod 'ReactiveObjC','~> 3.1.0' end
二、基础用法
1、模型到UI
RAC(_lblName,text) = RACObserve(self.person, name);
2、UI到模型
[RACObserve(self.person, name) subscribeNext:^(NSString *x){ @strongify(self) self.lblName.text = x; [self.btnName setTitle:x forState:UIControlStateNormal]; }];
[[RACObserve(self.person, name) filter:^BOOL(NSString *value) { return ![value hasPrefix:@"j"]; }] subscribeNext:^(id _Nullable x) { @strongify(self) self.lblName.text = [x stringByAppendingString:@"j"];; }];
3、模型到模型
[[RACSignal combineLatest:@[RACObserve(self, name),RACObserve(self.person, name)]] subscribeNext:^(RACTuple * _Nullable x) { @strongify(self) self.isSame = [x.first isEqualToString:x.second]; NSLog(@"%@",x.first); NSLog(@"%@",x[1]); }];
4、UI到UI
RAC(self.btnName,enabled) = [RACSignal combineLatest:@[self.tfdName.rac_textSignal,self.tfdPwd.rac_textSignal,self.tfdConfirmPwd.rac_textSignal] reduce:^(NSString *tfdname,NSString *pwd,NSString *confirmPwd){ NSLog(@"name:%@",tfdname); NSLog(@"pwd:%@",pwd); NSLog(@"confirmPwd:%@",confirmPwd); return @([tfdname length] > 0 && [pwd length] > 0 && [pwd isEqualToString:confirmPwd]); }];
5、绑定点击事件
方法一
[[self.btnName rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *sender){ // touch up inside }];
方法二: 当btnName上已经绑定signal时会报错 此时使用第二种方法
self.btnName.rac_command = [[RACCommand alloc]initWithSignalBlock:^(id input) { NSLog(@"touch action"); //input-btnName return [RACSignal empty]; }];
或者:
RACCommand *commandLogin = [[RACCommand alloc]initWithSignalBlock:^(id input) { NSLog(@"touch action"); return [RACSignal empty]; }]; [commandLogin.executionSignals subscribeNext:^(RACSignal *x) { [x subscribeCompleted:^{ NSLog(@"after touch action"); }]; }]; self.btnName.rac_command = commandLogin;