1.then
汽烦、contact
涛菠、merge
、combineLatest
then:是串型執(zhí)行 當信號A 執(zhí)行了[subscriber sendCompleted],才能往下走,訂閱的值是最后一個值
merger:把信號合并在一起俗冻,雖然也是串行執(zhí)行礁叔,但是是誰先來,誰先執(zhí)行
contact: 也是順序執(zhí)行迄薄,訂閱的值 是所有的值
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;
//串行執(zhí)行 (只是執(zhí)行最后的一個)
[[[self.s1 then:^RACSignal * _Nonnull{
return weakSelf.s2;
}] then:^RACSignal * _Nonnull{
return weakSelf.s3;
}] subscribeNext:^(id _Nullable x) {
NSLog(@"then_x = %@",x); //只打印s3的信號,這里面需要調(diào)用前面的信號 [subscriber sendCompleted] 或者error讥蔽,才會執(zhí)行
}];
//誰先來涣易,誰顯示
//如果是sendError 只能執(zhí)行,self.s1
[[[self.s1 merge:self.s2 ]merge:self.s3] subscribeNext:^(id _Nullable x) {
NSLog(@"merger_x = %@",x);
}];
//會順序的執(zhí)行冶伞,每一個新症,而 then 只能執(zhí)行最后一個值,并需要調(diào)用 sendCompleted
//如果是sendError 只能會執(zhí)行
[[[self.s1 concat:self.s2]concat:self.s3]subscribeNext:^(id _Nullable x) {
NSLog(@"concat_x = %@",x);
}];
//s1响禽,s2徒爹,s3 信號 同時到達會拼接成元組,也是一個同步的作用
//如果是 有 sendError芋类,下面的不會執(zhí)行
[[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 會順序的 執(zhí)行 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);
}