1.then
、contact
、merge
、combineLatest
then:是串型执行 当信号A 执行了[subscriber sendCompleted],才能往下走,订阅的值是最后一个值
merger:把信号合并在一起,虽然也是串行执行,但是是谁先来,谁先执行
contact: 也是顺序执行,订阅的值 是所有的值
combineLatest:是一个同步操作,会只要 多个信号同时到达 才去处理
- (void)viewDidLoad {
[super viewDidLoad];
self.s1 = [self customSignalWithTime:2];
self.s2 = [self customSignalWithTime:1];
self.s3 = [self customSignalWithTime:0.5];
__weak typeof(self)weakSelf = self;
//串行执行 (只是执行最后的一个)
[[[self.s1 then:^RACSignal * _Nonnull{
return weakSelf.s2;
}] then:^RACSignal * _Nonnull{
return weakSelf.s3;
}] subscribeNext:^(id _Nullable x) {
NSLog(@"then_x = %@",x); //只打印s3的信号,这里面需要调用前面的信号 [subscriber sendCompleted] 或者error,才会执行
}];
//谁先来,谁显示
//如果是sendError 只能执行,self.s1
[[[self.s1 merge:self.s2 ]merge:self.s3] subscribeNext:^(id _Nullable x) {
NSLog(@"merger_x = %@",x);
}];
//会顺序的执行,每一个,而 then 只能执行最后一个值,并需要调用 sendCompleted
//如果是sendError 只能会执行
[[[self.s1 concat:self.s2]concat:self.s3]subscribeNext:^(id _Nullable x) {
NSLog(@"concat_x = %@",x);
}];
//s1,s2,s3 信号 同时到达会拼接成元组,也是一个同步的作用
//如果是 有 sendError,下面的不会执行
[[RACSignal combineLatest:@[self.s1,self.s2,self.s3]] subscribeNext:^(RACTuple * _Nullable x) {
NSLog(@"x = %@",x);
}];
}
- (RACSignal *)customSignalWithTime:(NSTimeInterval )sleepTime{
return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
sleep(sleepTime);
dispatch_async(dispatch_get_main_queue(), ^{
if (0) { //模拟错误
[subscriber sendNext:@{@"data":[NSString stringWithFormat:@"fail__%f",sleepTime]}];
[subscriber sendError:[NSError errorWithDomain:@"com.lee.error" code:-1 userInfo:@{NSLocalizedDescriptionKey:[NSString stringWithFormat:@"fail__%f",sleepTime]}]];
} else { //模拟正确
[subscriber sendNext:@{@"data":[NSString stringWithFormat:@"sucess__%f",sleepTime]}];
[subscriber sendCompleted];
}
});
});
return [RACDisposable disposableWithBlock:^{
}];
}];
}
2. flatMap
、map
、filter
flatMap:会把多个sequence 合成一个 sequence
map:改变value的值
filter:过滤一些值
- (void)flatMap {
RACSequence * s1 = @[@(1),@(2),@(3)].rac_sequence;
RACSequence * s2 = @[@(1),@(3),@(9)].rac_sequence;
//flattenMap:返回一个新的sequence 信号
RACSequence * s3 = [@[s1,s2].rac_sequence flattenMap:^__kindof RACSequence * _Nullable(RACSequence * sequence) {
//这里的sequence 会顺序的 执行 s1、s2
// map 是改变 value值
//filter :过滤 value值
return [[sequence map:^id _Nullable(id _Nullable value) {
if ([value integerValue] %3 == 0) {
return @([value integerValue] * 2);
} else {
return value;
}
}] filter:^BOOL(id _Nullable value) {
if ([value integerValue] %2 == 0) {
return true;
} else {
return false;
}
}];
}];
NSLog(@"s3 = %@",s3.array);
}