RAC 函数式响应式编程框架
类似的框架:Masonry、AFNetworking、
订阅信号
- (void) reactiveObjTest {
//1.订阅信号 -- 在实际开发中,就是提供给外界订阅的
/*
创建一个可变数组变量 _subscribers
*/
RACSubject *subject = [RACSubject subject];
//2.订阅信号 -- 代理\通知对比
//相当于代理 objc.delegate = self;
/*
调用这个方法所做的事情
1. 创建订阅者对象
2. 将Block放到订阅者对象中
3. 将订阅者对象放到_subscriber数组里面
*/
[subject subscribeNext:^(id _Nullable x) {//调用这个方法的返回值,可以用来取消订阅
NSLog(@"%@", x);
}];
//3.注册信号
/*
遍历信号对象中的数组,取出订阅者,调用订阅者对象中的Block,然后执行
*/
[subject sendNext:@"O(∩_∩)O哈!"];
}
输出:2019-06-06 15:34:46.583177+0800 Genealogy[6591:256569] O(∩_∩)O哈!
源码:
+ (instancetype)subject {
return [[self alloc] init];
}
- (instancetype)init {
self = [super init];
if (self == nil) return nil;
//取消订阅信号
_disposable = [RACCompoundDisposable compoundDisposable];
_subscribers = [[NSMutableArray alloc] initWithCapacity:1];
return self;
}
- (void)dealloc {
//取消订阅
[self.disposable dispose];
}
- (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock {
NSCParameterAssert(nextBlock != NULL);
RACSubscriber *o = [RACSubscriber subscriberWithNext:nextBlock error:NULL completed:NULL];
return [self subscribe:o];
}
+ (instancetype)subscriberWithNext:(void (^)(id x))next error:(void (^)(NSError *error))error completed:(void (^)(void))completed {
RACSubscriber *subscriber = [[self alloc] init];
//next block保存在我们新创建的订阅者subscriber中了
subscriber->_next = [next copy];
subscriber->_error = [error copy];
subscriber->_completed = [completed copy];
return subscriber;
}
对私有方法进行订阅
GFamilyView.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface GFamilyView : UIView
@end
NS_ASSUME_NONNULL_END
GFamily.m
@interface GFamilyView ()
@property(nonatomic, retain)UIButton *buildFamilyBtn;
@end
@implementation GFamilyView
- (void) buildFamilyAction:(UIButton *)sender {
}
@end
GMyFamilyController.m
调用
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"我的家族";
[self addSubViews];
//这里使用了运行时,调用其私有的方法
[[self.familyView rac_signalForSelector:@selector(buildFamilyAction:)] subscribeNext:^(RACTuple * _Nullable x) {//x 是buildFamilyAction参数的集合
NSLog(@"观察到了按钮点击!");
}];
}
输出:2019-06-06 17:13:19.408324+0800 Genealogy[7979:352547] 观察到了按钮点击!
RAC的KVO
导入文件:#import <NSObject+RACKVOWrapper.h>
GMyFamilyController.m 文件
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"我的家族";
//函数式编程思想
[self.familyView rac_observeKeyPath:@"frame" options:NSKeyValueObservingOptionNew observer:self block:^(id value, NSDictionary *change, BOOL causedByDealloc, BOOL affectedOnlyLastComponent) {
//
NSLog(@"%@", change);
}];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.familyView.frame = CGRectMake(0, 0, 50, 50);
}
输出:2019-06-06 18:04:55.406959+0800 Genealogy[8733:402957] { kind = 1; new = "NSRect: {{0, 0}, {50, 50}}"; }
转载于:https://www.jianshu.com/p/a4955053792e