03RAC--01

2018-05-17  本文已影响4人  myk
//将txf1发送的信号和lbl绑定;即self.lbl.text = self.txf1.text;
RAC(self.lbl, text) = self.txf1.rac_textSignal;
//但是只有在self.txf1结束编辑的时候才会调用,在self.txf1还是第一响应的时候不会调用
[RACObserve(self.txf1, text) subscribeNext:^(id x) {
        NSLog(@"x === %@", x);
    }];
    RAC(self.btn, backgroundColor) = [self.enableSignal map:^id(NSNumber *numBool) {
        return [numBool boolValue] ? [UIColor greenColor] : [UIColor redColor];
    }];

 //创建信号
    RACSignal *s1 = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        //发送信号
        [subscriber sendNext:@"22"];
        return nil;
    }];
    //订阅信号
    [s1 subscribeNext:^(id x) {
        NSLog(@"x1 === %@", x);
    }];
//打印结果:22
//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);
}];
上一篇 下一篇

猜你喜欢

热点阅读