iOS简单使用RAC

作者: _moses | 来源:发表于2017-12-26 23:57 被阅读331次

    GitHub地址:ReactiveCocoa

    RAC.png

    一、响应式编程就是实时响应某个事件

    // 创建信号
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        NSLog(@"Hello");
        // 发送信号
        [subscriber sendNext:@"This is RAC"];
        return nil;
    }];
    // 订阅信号
    [signal subscribeNext:^(id  _Nullable x) {
        NSLog(@"%@",x);
    }];
    

    二、RAC很强大,一行代码搞定以前的事件监听

    举几个实际使用案例
    1. TargetAction转Block
    ①UITextField(实时监听输入框内容)

    [[self.textField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        NSLog(@"%@", x);
    }];
    

    ②UITextField(实时监听多个输入框内容)

    [[RACSignal combineLatest:@[self.nameTextField.rac_textSignal, self.pwdTextField.rac_textSignal]] subscribeNext:^(RACTuple * _Nullable x) {
        NSLog(@"name : %@, pwd : %@", x.first, x.second);
    }];
    
    [[[RACSignal combineLatest:@[self.nameTextField.rac_textSignal, self.pwdTextField.rac_textSignal]] reduceEach:^id _Nullable(NSString *name, NSString *pwd) {
        return @(name.length && pwd.length);
    }] subscribeNext:^(id  _Nullable x) {
        NSLog(@"%zd", [x boolValue]);
    }];
    

    ③UIButton(Button点击事件)

    [[self.button rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSLog(@"%@",x);
    }];
    

    2. 通知转Block

    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidBecomeActiveNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        NSLog(@"%@",x);
    }];
    

    3.KVO转Block

    [RACObserve(self.person, name) subscribeNext:^(id  _Nullable x) {
        self.label.text = x;
    }];
    

    三、注意事项:

    RAC使用@weakify(self);@strongify(self);来避免block循环引用

    @weakify(self);
    [[self.textField rac_textSignal] subscribeNext:^(NSString * _Nullable x) {
        @strongify(self);
        self.textField.text = @"Hello";
    }];
    

    相关文章

      网友评论

        本文标题:iOS简单使用RAC

        本文链接:https://www.haomeiwen.com/subject/qfaegxtx.html