获得一个信号:
单元信号
RACSignal *signal1 = [RACSignal return:@"Some value"];
RACSignal *signal2 = [RACSignal error:[NSError new]];
RACSignal *signal3 = [RACSignal empty];
RACSignal *signal4 = [RACSignal never];
动态信号
RACSignal *signal5 = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
[subscriber sendNext:@1];
[subscriber sendNext:@2];
[subscriber sendError:[NSError new]];
[subscriber sendCompleted];
return [RACDisposable disposableWithBlock:^{
NSLog(@"信号结束");
}];
}];
Cocoa桥接:
// 给View的方法添加一个信号,当这个信号被订阅,同时执行了它的这个方法时,就会给订阅者发送内容。
UIView *view = [UIView new];
view.backgroundColor = [UIColor redColor];
RACSignal *signal6 = [view rac_signalForSelector:@selector(setFrame:)];
[signal6 subscribeNext:^(id x) {
NSLog(@"next value is %@",x);
}];
[view setFrame:CGRectMake(0, 0, 375, 264)];
RACSignal *signal7 = [[UIButton new] rac_signalForControlEvents:UIControlEventTouchUpInside];
RACSignal *signal8 = [[UIView new] rac_willDeallocSignal];
RACSignal *signal9 = RACObserve([UIView new], backgroundColor);
信号变化:
RACSignal *signal10 = [signal1 map:^id(NSString *value) {
return [value substringToIndex:1];
}];
序列转换:
RACSequence *sequence1 = [RACSequence return:@1];
RACSignal *signal11 = sequence1.signal;
订阅方法:
[[signal11 subscribeNext:^(id x) {
NSLog(@"next value is %@",x);
} error:^(NSError *error) {
NSLog(@"error:%@",error);
} completed:^{
NSLog(@"completed");
}] dispose];
Cocoa桥接:
RACSignal *sg1 = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
[subscriber sendNext:@"网络请求数据1"];
return nil;
}];
RACSignal *sg2 = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
[subscriber sendNext:@"网络请求数据2"];
return nil;
}];
RACSignal *sg3 = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
[subscriber sendNext:@"网络请求数据3"];
return nil;
}];
// Cocoa桥接
// 当全部信号执行完毕之后,最后刷新UI的问题
// rac_liftSelector
// 类似于dispatch_group 中的组
// 多线程中的组 等所有的请求都完毕之后 去更新UI
// 信号跟参数的个数要一一对应
[self rac_liftSelector:@selector(updateUI:str:str:) withSignals:sg1, sg2, sg3, nil];
[self rac_liftSelector:@selector(updateUI:str:str:) withSignalsFromArray:@[sg1, sg2, sg3]];
- (void)updateUI:(id)str1 str:(id)str2 str:(id)str3 {
// 回传过来
NSLog(@"%@-%@-%@",str1,str2,str3);
}
订阅过程:
RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
[subscriber sendNext:@1];
[subscriber sendNext:@2];
[subscriber sendCompleted];
return [RACDisposable disposableWithBlock:^{
NSLog(@"dispose");
}];
}];
RACDisposable *disposable = [signal subscribeNext:^(id x) {
NSLog(@"next%@",x);
} error:^(NSError *error) {
NSLog(@"error:%@",error);
} completed:^{
NSLog(@"completed");
}];
[disposable dispose];
网友评论