RAC简单示例
信号订阅与发送
// 1.创建信号(默认是冷信号)
RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
// 3. 只要被订阅就会被执行这个block
// 3.1 在这里发出各种信号
[subscriber sendNext:@"send next"];
[subscriber sendError:[[NSError alloc] initWithDomain:@"com.gk.error" code:100861 userInfo:@{@"des":@"my error"}]];
// 3.2 如果不再发送信号,最好发送完成信号。内部会自动调用[RACDisposable disposable]取消订阅。
[subscriber sendCompleted];
// 3.3 销毁信号
return [RACDisposable disposableWithBlock:^{
// 销毁信号,取消订阅的时候会执行这个block。
NSLog(@"game over");
}];
}];
// 2.订阅信号(订阅即激活)
[signal subscribeNext:^(id _Nullable x) {
NSLog(@"recive next = %@", x);
} error:^(NSError * _Nullable error) {
NSLog(@"recive error.domain = %@, error.code = %ld, error.userInfo = %@", error.domain, error.code, error.userInfo);
} completed:^{
NSLog(@"recive completed");
}];
使用示例
// kvo
[RACObserve(self, name) subscribeNext:^(id _Nullable x) {
NSLog(@"observe --- %@", x);
}];
// notification
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardDidShowNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
NSLog(@"notify --- %@", x);
}];
// delegate
[[self rac_signalForSelector:@selector(textFieldDidBeginEditing:) fromProtocol:@protocol(UITextFieldDelegate)] subscribeNext:^(RACTuple * _Nullable x) {
NSLog(@"delegate --- %@", x);
}];
// event
[[self.tf rac_signalForControlEvents:UIControlEventEditingChanged] subscribeNext:^(__kindof UITextField * _Nullable x) {
NSLog(@"event1 --- %@", x.text);
}];
[[self.btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
NSLog(@"event2 --- %@", x);
}];
self.btn.rac_command = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id _Nullable input) {
NSLog(@"%@", input);
return [RACSignal empty];
}];
// gesture
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
[self.lab addGestureRecognizer:tap];
self.lab.userInteractionEnabled = YES;
[tap.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
NSLog(@"gesture --- %@", x);
}];
// sequence
NSArray *arr = @[@"lh", @"lhe"];
[arr.rac_sequence.signal subscribeNext:^(id _Nullable x) {
NSLog(@"arr --- %@", x);
}];
NSDictionary *dic = @{@"name":@"lh", @"age":@"18"};
[dic.rac_sequence.signal subscribeNext:^(RACTwoTuple _Nullable x) {
NSLog(@"dic --- %@", x);
}];
// timer
[[RACSignal interval:1 onScheduler:[RACScheduler schedulerWithPriority:(RACSchedulerPriorityHigh) name:@" com.gk.ractimer"]] subscribeNext:^(NSDate * _Nullable x) {
NSLog(@"timer --- %@",[NSThread currentThread]);
}];
网友评论