//将txf1发送的信号和lbl绑定;即self.lbl.text = self.txf1.text;
RAC(self.lbl, text) = self.txf1.rac_textSignal;
- 一句代码,就将Label和TextField绑定,保证Label的内容和TextField保持一致;
-
RACObserve()和RAC()
- RACObserve()是观察者模式
//但是只有在self.txf1结束编辑的时候才会调用,在self.txf1还是第一响应的时候不会调用
[RACObserve(self.txf1, text) subscribeNext:^(id x) {
NSLog(@"x === %@", x);
}];
- RAC()是绑定,将btn的backgroundColor属性和self.enableSignal绑定
RAC(self.btn, backgroundColor) = [self.enableSignal map:^id(NSNumber *numBool) {
return [numBool boolValue] ? [UIColor greenColor] : [UIColor redColor];
}];
-
RACSignal(信号)
- (1) 使用RACSignal创建一个信号,然后发送信号,最后订阅者订阅信号
//创建信号
RACSignal *s1 = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
//发送信号
[subscriber sendNext:@"22"];
return nil;
}];
//订阅信号
[s1 subscribeNext:^(id x) {
NSLog(@"x1 === %@", x);
}];
//打印结果:22
- (2)输入用户名和密码之后,通过判断改变按钮的颜色,判断按钮的enable属性
//map 将NSString映射成Number类型
RACSignal *signal1 = [self.txf1.rac_textSignal map:^id(NSString *text) {
return @([text isEqualToString:@"text"]);
}];
RACSignal *signal2 = [self.txf2.rac_textSignal map:^id(NSString *text) {
return [NSNumber numberWithInteger:text.length];
}];
//合并两个信号
self.enableSignal = [RACSignal combineLatest:@[signal1, signal2] reduce:^id(NSNumber *num1, NSNumber *num2){
return @([num1 boolValue] && [num2 boolValue]);
}];
//通过信号改变按钮的属性
[self.enableSignal subscribeNext:^(NSNumber *numBool) {
self.btn.enabled = [numBool boolValue];
[UIView animateWithDuration:1 animations:^{
self.btn.backgroundColor = [numBool boolValue] ? [UIColor greenColor] : [UIColor redColor];
}];
}];
创建VM实现登录
.h文件
-(void)pwd:(NSString *)pwd username:(NSString *)username complete:(void(^)(bool isSuccess))completeHandle;
.m文件
-(void)pwd:(NSString *)pwd username:(NSString *)username complete:(void(^)(bool isSuccess))completeHandle{
bool isSuccess = ([pwd isEqualToString:@"111"] && [username isEqualToString:@"111"]);
completeHandle(isSuccess);
}
-(RACSignal *)viewModel{
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
[self.vm pwd:self.txf1.text username:self.txf2.text complete:^(bool isSuccess) {
[subscriber sendNext:@(isSuccess)];
[subscriber sendCompleted];
}];
return [RACDisposable disposableWithBlock:^{
NSLog(@"销毁了");
}];
}];
}
//doNext:你可以看到doNext:是直接跟在按钮点击事件的后面。而且doNext: block并没有返回值。因为它是附加操作,并不改变事件本身;把按钮置为不可点击
//这里为什么用flattenMap而不用Map
//flattenMap:使用 flattenMap 的时候,block 中应该 return 你想要的信号
//Map:使用 map 的时候,block 中应该 return 你后面希望接收到的值
//因为 [self viewModel] 方法返回的是一个信号,所以要用flattenMap
[[[[self.btn rac_signalForControlEvents:UIControlEventTouchUpInside]
doNext:^(id x) {
self.btn.enabled = NO;
}] flattenMap:^RACStream *(id value) {
return [self viewModel];
}] subscribeNext:^(NSNumber *isSuccess) {
self.btn.enabled = YES;
NSLog(@"isSuccess ==== %@", isSuccess);
}];
网友评论