Reactive Cocoa 的简单使用

Die there is life, that is to say, there is life there is hope.

1.什么是 ReactiveSwift?

ReactiveSwift offers composable, declarative and flexible primitives that are built around the grand concept of streams of values over time. These primitives can be used to uniformly represent common Cocoa and generic programming patterns that are fundamentally an act of observation. 简而言之,用平常话来说,就是代替各种代理、各种target - action、 各种监听的一个三方框架。

2.从官方的文档上看,先有 ReactiveSwift 才有 ReactiveObjC

ReactiveObjC is inspired by functional reactive programming. Rather than using mutable variables which are replaced and modified in-place, RAC provides signals (represented by RACSignal) that capture present and future values.RAC里提供信号(signals)这个介质来传递值给接收者。

3.一些常见的使用方法
  • Button点击事件
self.cancelButton.rac_command = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
[self.navigationController popViewControllerAnimated:YES];
return [RACSignal empty];
}];
  • 伪代理

在 B 页面创建,建议使用全局变量:

RACSubject *delegate =  [RACSubject subject];
[self.delegate sendNext:@"要传的值"];

在 A 页面接收:

self.B.delegate subscribeNext:^(id  _Nullable x) {
NSLog(@"返回的值%@",x);
}];

  • 数组的运用

RAC里的数组翻译过来叫 元组。 RACTuple *buttonArray = [RACTuple tupleWithObjects:@"1", @"2", @"3", @"4", @"5", nil];

数组的遍历:


[self.buttonArray.rac_sequence.signal subscribeNext:^(UIButton *btn) {
//我这里装的是UIButton,遍历出来的就是button按钮

//跟UI相关的必须放到主线程
dispatch_async(dispatch_get_main_queue(), ^{

if (btn.tag<tag) {
btn.selected = button.selected;
}else if (btn.tag!=tag && btn.tag > tag){
btn.selected = NO;
}
});

}];