RAC使用

什么是RAC

ReactiveCocoa框架具有响应式编程的特点,能精简代码,优化逻辑,去除了协议代理等的引用

RAC能干什么

使用事件流统一了OC的事件处理和异步处理
-委托
-通知
-UIKit事件
-KVO
-回调block

RAC使用示例

1.代替委托

- (RACSignal *)rac_signalForSelector:(SEL)selector fromProtocol:(Protocol *)protocol{}

2.代替通知

[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] subscribeNext:^(id x) {
NSLog(@"%@",x);
}];

3.代替UIKit事件

[[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
}];
[[(UITextView *)text rac_textSignal] subscribeNext:^(id x) {
}];

4.代替KVO

[[button rac_valuesForKeyPath:@"frame" observer:nil] subscribeNext:^(id x) {
}];

//此方法订阅next事件

- (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock{}
//如果不想订阅
[(RACDisposable*)disposable dispose];

//多个信号都接收到了才执行selector

- (RACSignal *)rac_liftSelector:(SEL)selector withSignalsFromArray:(NSArray *)signals{}

//多播信号 我的理解就是有多处订阅信号,创建信号的block只执行一次

- (void)test {
__block NSUInteger b = a;
RACSignal *sourceSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id _Nonnull subscriber) {
b++;
NSLog(@"调用了数据:%@", [NSDate date]);
[subscriber sendNext:nil];
return nil;
}];
RACMulticastConnection *connection = [sourceSignal publish];
[connection.signal subscribeNext:^(id _Nullable x) {
NSString *dataString = [[NSString alloc] initWithData:x encoding:NSUTF8StringEncoding];
NSLog(@"A处调用了数据:%@ b = %ld", dataString,b);
}];
[connection.signal subscribeNext:^(id _Nullable x) {
NSString *dataString = [[NSString alloc] initWithData:x encoding:NSUTF8StringEncoding];
NSLog(@"B处调用了数据:%@ b = %ld", dataString,b);
}];
[connection connect];
}

输出

2017-06-22 16:43:02.641 ReactiveCocoaTest[16910:634484] 调用了数据:2017-06-22 08:43:02 +0000
2017-06-22 16:43:02.641 ReactiveCocoaTest[16910:634484] A处调用了数据: b = 1
2017-06-22 16:43:02.642 ReactiveCocoaTest[16910:634484] B处调用了数据: b = 1

//RACCommand

[button setRac_command:[[RACCommand alloc] initWithEnabled:nil signalBlock:^RACSignal *(id input) {
        return [RACSignal createSignal:^RACDisposable *(id subscriber) {
            NSLog(@"Clicked");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [subscriber sendNext:[[NSDate date] description]];
                [subscriber sendCompleted];
            });
            return [RACDisposable disposableWithBlock:^{
            }];
        }];
    }]];

//bind

UIAlertView alertView = [[UIAlertView alloc] initWithTitle:@"RAC" message:@"RAC TEST" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"other", nil];
[[alertView.rac_buttonClickedSignal bind:^RACStreamBindBlock{
return ^RACStream
(id value,BOOL *stop){
return [RACReturnSignal return:[NSString stringWithFormat:@"%@",value]];
};
}] subscribeNext:^(id x) {
NSLog(@"%@",x);
}];

你可能感兴趣的:(RAC使用)