//將txf1發(fā)送的信號和lbl綁定亚脆;即self.lbl.text = self.txf1.text;
RAC(self.lbl, text) = self.txf1.rac_textSignal;
- 一句代碼做院,就將Label和TextField綁定,保證Label的內(nèi)容和TextField保持一致濒持;
-
RACObserve()和RAC()
- RACObserve()是觀察者模式
//但是只有在self.txf1結(jié)束編輯的時候才會調(diào)用键耕,在self.txf1還是第一響應(yīng)的時候不會調(diào)用
[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創(chuàng)建一個信號,然后發(fā)送信號柑营,最后訂閱者訂閱信號
//創(chuàng)建信號
RACSignal *s1 = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
//發(fā)送信號
[subscriber sendNext:@"22"];
return nil;
}];
//訂閱信號
[s1 subscribeNext:^(id x) {
NSLog(@"x1 === %@", x);
}];
//打印結(jié)果: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];
}];
}];
創(chuàng)建VM實(shí)現(xiàn)登錄
- 創(chuàng)建一個VM,通過輸入賬號密碼之后調(diào)用block
.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:是直接跟在按鈕點(diǎn)擊事件的后面官套。而且doNext: block并沒有返回值酒奶。因?yàn)樗歉郊硬僮鳎⒉桓淖兪录旧?把按鈕置為不可點(diǎn)擊
//這里為什么用flattenMap而不用Map
//flattenMap:使用 flattenMap 的時候虏杰,block 中應(yīng)該 return 你想要的信號
//Map:使用 map 的時候讥蟆,block 中應(yīng)該 return 你后面希望接收到的值
//因?yàn)?[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);
}];
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者