iOS简单使用RAC

GitHub地址:ReactiveCocoa

iOS简单使用RAC_第1张图片
RAC.png

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

// 创建信号
RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id  _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)