iOS 响应式编程 ReactiveCocoa的使用

1、KVO
/// KVO
- (void)racKVO {
    
    [RACObserve(self, index) subscribeNext:^(id  _Nullable x) {
        NSLog(@"index  = %@",x);
    }];
    
    [[RACObserve(self, index) filter:^BOOL(id  _Nullable value) {
            NSString * number = [NSString stringWithFormat:@"%@",value];
            return  [number integerValue] > 3;
        }] subscribeNext:^(id  _Nullable x) {
            NSLog(@"index1 = %@",x);
        }];
}

2、对象遍历

/// 对象遍历
- (void)racTraverse {

    self.strArr = @[@"11",@"22",@"33"];
    
    self.strDict = @{@"name":@"lise",@"age":@"16"};
    
    [self.strArr.rac_sequence.signal subscribeNext:^(id  _Nullable x) {
        NSLog(@"数组遍历 = %@",x);
    }];

    [self.strDict.rac_valueSequence.signal subscribeNext:^(id  _Nullable x) {
        NSLog(@"dict = %@",x);
    }];
    
    
//  map: 映射, 返回有映射值的信号
    [[self.strArr.rac_sequence.signal map:^id _Nullable(id  _Nullable value) {
        NSLog(@"value = %@",value);
        return  [NSString stringWithFormat:@"%@ number",value];
    }] subscribeNext:^(id  _Nullable x) {
        NSLog(@"xxx = %@",x);
    }];
}

3、文本输入监听

/// 输入框文本监听
- (void)racTextChange {
    
    [self.textField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        NSLog(@"点击TextField 文本 = %@",x);
    }];
}
4、点击事件
/// 点击事件
- (void)racClickEnent {
    
    [[self.senderBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSLog(@"点击Button");
    }];
}

5、反向传值

A、

- (void)racDelegateEvent {
    
    [[self.senderBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        ViewControllerB *b = [[ViewControllerB alloc]init];
        [b.subject subscribeNext:^(id  _Nullable x) {
                NSLog(@"接收成功---");
        }];
        [self presentViewController:b animated:YES completion:nil];
    }];
    
}

B、

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (self.subject) {
        [self.subject sendNext:@"发送成功"];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (RACSubject *)subject {
    if (!_subject) {
        _subject = [RACSubject subject];
    }
    return _subject;
}

6、通知

/// 通知监听
- (void)racNotificationCenter {
    //用rac通知不需要在dealloc 移除通知
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"NOTI" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        NSLog(@"通知x = %@",x);
        }];
}

7、Concat

- (void)racConcat{
    
    //创建一个信号管A
    RACSignal *siganlA = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [subscriber sendNext:@"吃饭"];
        [subscriber sendCompleted];
        return nil;
        
    }];
    
    //创建一个信号管B
    RACSignal *siganlB = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
       
        [subscriber sendNext:@"吃的饱饱的,才可以睡觉的"];
        [subscriber sendCompleted];
        return nil;
    }];
    
    //串联管A和管B
    RACSignal *concatSiganl = [siganlA concat:siganlB];
    //串联后的接收端处理 ,两个事件,走两次,第一个打印siggnalA的结果,第二次打印siganlB的结果
    [concatSiganl subscribeNext:^(id x) {
        NSLog(@"x = %@",x);
        
    }];
    
    /*
     2020-12-29 15:23:36.986317+0800 CMF[9981:249102] x = 吃饭
     2020-12-29 15:23:36.986461+0800 CMF[9981:249102] x = 吃的饱饱的,才可以睡觉的
     */

}

8、Merge(合并)

/// 合并
- (void)racMerge{
  //创建信号A
    RACSignal *siganlA = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [subscriber sendNext:@"纸厂污水"];
        [subscriber sendCompleted];
        return nil;
    }];
    
    //创建信号B
    RACSignal *siganlB = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
       
        [subscriber sendNext:@"电镀厂污水"];
        [subscriber sendCompleted];
        return nil;
    }];
    
    //并联两个信号,根上面一样,分两次打印
    RACSignal *mergeSiganl = [RACSignal merge:@[siganlA,siganlB]];
    [mergeSiganl subscribeNext:^(id x) {
        NSLog(@"%@",x);
    }];
    
    /*
     2020-12-29 15:22:14.554204+0800 CMF[9929:247474] 纸厂污水
     2020-12-29 15:22:14.554359+0800 CMF[9929:247474] 电镀厂污水
     */
}

9、CombineLatest

/// 组合
- (void)combineLatest {
    
    RACSubject *sub1 = [RACSubject subject];
    RACSubject *sub2 = [RACSubject subject];
    
    [[RACSignal combineLatest:@[sub1,sub2] reduce:^(NSString *num1, NSString *num2){
        return [NSString stringWithFormat:@"%@-%@",num1,num2];
        }] subscribeNext:^(id  _Nullable x) {
            
        }];
    //组合信号
    [[RACSignal combineLatest:@[sub1,sub2] reduce:^(NSString *letter, NSString *number){
        
        return [letter stringByAppendingString:number];
    }] subscribeNext:^(id x) {
        NSLog(@"%@",x);
        
    }];
    
    
    [sub1 sendNext:@"A"];
    [sub1 sendNext:@"B"];
    
    [sub2 sendNext:@"1"]; //此时有结果打印,打印结果B1
    [sub1 sendNext:@"C"]; //打印结果C1
    [sub2 sendNext:@"2"]; //打印结果C2
      
}

10、压缩合流

// 压缩合流
- (void)zipTuple {
    
    RACSignal *subject1 = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [subscriber sendNext:@"红"];
        [subscriber sendCompleted];
        return  nil;
    }];
    
    RACSignal *subject2 = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [subscriber sendNext:@"绿"];
        [subscriber sendCompleted];
        return  nil;
    }];
    
    
    //合流后处理的是压缩包,需要解压后才能取到里面的值
    [[subject1 zipWith:subject2] subscribeNext:^(id  _Nullable x) {
        
        //解压缩
        RACTupleUnpack(NSString *str1, NSString *str2) = x;
        NSLog(@"str1 = %@ , str2 = %@ ", str1, str2);
    }];
    
    /*
     2020-12-29 15:21:30.584915+0800 CMF[9905:246624] str1 = 红 , str2 = 绿
     */
}

11、filter(过滤)

/// 过滤
- (void)filterValue {
    
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [subscriber sendNext:@(14)];
        [subscriber sendNext:@(16)];
        [subscriber sendNext:@(24)];
        [subscriber sendNext:@(11)];
        [subscriber sendNext:@(6)];
        [subscriber sendCompleted];
        return nil;
    }];
    
    [[signal filter:^BOOL(NSNumber * value) {
        return value.intValue >= 14;
        }] subscribeNext:^(id  _Nullable x) {
            NSLog(@"filter-Value = %@",x);
        }];
    
    /*
     2020-12-29 13:51:38.320945+0800 CMF[7598:188614] filter-Value = 14
     2020-12-29 13:51:38.321104+0800 CMF[7598:188614] filter-Value = 16
     2020-12-29 13:51:38.321206+0800 CMF[7598:188614] filter-Value = 24
     */
}

12、flattenMap

- (void)flattenMap {
    
    RACSignal *siganl = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        NSLog(@"打蛋液");
        [subscriber sendNext:@"蛋液"];
        [subscriber sendCompleted];
        return nil;
        
    }];
    
    //对信号进行秩序秩序的第一步
    siganl = [siganl flattenMap:^RACSignal *(NSString *value) {
        //处理上一步的RACSiganl的信号value.这里的value=@"蛋液"
        NSLog(@"把%@倒进锅里面煎",value);
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [subscriber sendNext:@"煎蛋"];
            [subscriber sendCompleted];
            return nil;
            
        }];
        
    }];
    //对信号进行第二步处理
    siganl = [siganl flattenMap:^RACSignal *(id value) {
        NSLog(@"把%@装载盘里",value);
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [subscriber sendNext:@"上菜"];
            [subscriber sendCompleted];
            return nil;
        }];
        
    }];
    
    //最后打印 最后带有===上菜
    [siganl subscribeNext:^(id x) {
        NSLog(@"====%@",x);
    }];
        
    /*
     2020-12-29 14:31:32.718247+0800 CMF[8526:208438] 打蛋液
     2020-12-29 14:31:32.718362+0800 CMF[8526:208438] 把蛋液倒进锅里面煎
     2020-12-29 14:31:32.718478+0800 CMF[8526:208438] 把煎蛋装载盘里
     2020-12-29 14:31:32.718561+0800 CMF[8526:208438] ====上菜
     */
    
}

13、Command (命令)

/// 命令
- (void)racCommand {
    RACCommand *command = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        NSLog(@"这是真的吗 - %@",input);
        return  [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            return  nil;
        }];
    }];
    
    [command execute:@"来了"];
    
    /*
     2020-12-29 15:20:57.876701+0800 CMF[9883:245859] 这是真的吗 - 来了
     */
}

14、Delay(延时)

/// 延时
- (void)racDelay {
    
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [subscriber sendNext:@"延时处理"];
        [subscriber sendCompleted];
        return  nil;
    }];
    
    [[signal delay:3] subscribeNext:^(id  _Nullable x) {
        NSLog(@"时间到了 - %@",x);
    }];
    
    /*
     2020-12-29 14:57:54.780489+0800 CMF[9213:227273] 时间到了 - 延时处理
     */
}

15、replay

/// 重复
- (void)racReplay {
    
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [subscriber sendNext:@"重复处理"];
        [subscriber sendCompleted];
        return  nil;
    }];
    
    RACSignal *replaySigal = [signal replay];
    [replaySigal subscribeNext:^(id  _Nullable x) {
        NSLog(@"replay = %@",x);
    }];

    [replaySigal subscribeNext:^(id  _Nullable x) {
            NSLog(@"replay11 = %@",x);
    }];
}

16、定时器

/// 定时器,每隔3秒执行一次
- (void)racInterval {
    
    RACSignal *signal = [RACSignal interval:3 onScheduler:[RACScheduler mainThreadScheduler]];
    
    [signal subscribeNext:^(id  _Nullable x) {
            NSLog(@"xxx = %@",x);
    }];
    
    /*
     2020-12-29 15:12:45.495541+0800 CMF[9622:238538] xxx = Tue Dec 29 15:12:45 2020
     2020-12-29 15:12:48.496308+0800 CMF[9622:238538] xxx = Tue Dec 29 15:12:48 2020
     2020-12-29 15:12:51.495188+0800 CMF[9622:238538] xxx = Tue Dec 29 15:12:51 2020
     ......
     */
    
}

17、键值绑定

RACSignal * validEmailSignal = [self.textField.rac_textSignal map:^id (NSString *value){
    return @([value rangeOfString:@"@"].location != NSNotFound);
}];

RAC(self.button, enabled) = validEmailSignal;

RAC(self.textField, textColor) = [validEmailSignal map: ^id (id value){
    if([value boolValue]){
        return [UIColor greenColor];
    }else{
        return [UIColor redColor];
    }
}];

文章参考整理自

1、iOS函数响应式编程以及ReactiveCocoa的使用

2、iOS ReactiveCocoa 最全常用API整理(可做为手册查询)

推荐阅读更多精彩内容