您的当前位置:首页iOS RAC - 映射

iOS RAC - 映射

2024-12-13 来源:哗拓教育



在之前的集合文章中我们使用到了map,他是RAC中主要的两个映射方法之一
还有一个是flattenMap,这两个方法是将我们的信号源的内容映射成为一个新的信号。

先看看我们平时的用法:

    RACSubject * subject = [RACSubject subject];
    
    [subject subscribeNext:^(id  _Nullable x) {
        NSLog(@"%@",x);
    }];
    
    [subject sendNext:@"what happend?"];



然后先看看flattenMap
其实flattenMap内部也是在bind,如下图所示

内部实现

之前bind的用法我们已经了解过了,照葫芦画瓢

    RACSubject * subject = [RACSubject subject];
    
    RACSignal * signal = [subject flattenMap:^__kindof RACSignal * _Nullable(id  _Nullable value) {
        return [RACReturnSignal return:value];
    }];
    
    [signal subscribeNext:^(id  _Nullable x) {
        NSLog(@"%@",x);
    }];
    
    [subject sendNext:@"what happend?"];

现在我们把发送的数据稍微处理一下

    RACSubject * subject = [RACSubject subject];
    
    [[subject flattenMap:^__kindof RACSignal * _Nullable(id  _Nullable value) {
        value = [NSString stringWithFormat:@"%@ 你别问我,我也不知道!",value];
        return [RACReturnSignal return:value];
    }] subscribeNext:^(id  _Nullable x) {
        NSLog(@"%@",x);
    }];
    
    [subject sendNext:@"what happend?"];
处理数据



然后我们在使用map完成上面的功能

    RACSubject * subject = [RACSubject subject];
    
    [[subject map:^id _Nullable(id  _Nullable value) {
        return [NSString stringWithFormat:@"%@ 你别问我,我也不知道!",value];
    }] subscribeNext:^(id  _Nullable x) {
        NSLog(@"%@",x);
    }];
    
    [subject sendNext:@"what happend?"];
map



然后在多发几次数据看看会发生什么?

多发数据



两者对比,是不是map要更简洁呢?既然map要比flattenMap更好用,那么为什么还有flattenMap呢?
flattenMap当然是有他独特的地方啦!在开发过程中,他更适合用于处理信号中的信号

    RACSubject * subjectOfSignal = [RACSubject subject];
    
    RACSubject * subject1 = [RACSubject subject];
    
    [subjectOfSignal sendNext:subject1];
    
    [subject1 sendNext:@"弄啥嘞"];



之前我们的做法有两种:
第一种:双重订阅

    RACSubject * subjectOfSignal = [RACSubject subject];
    
    RACSubject * subject1 = [RACSubject subject];
    
    [subjectOfSignal subscribeNext:^(id  _Nullable x) {
        [x subscribeNext:^(id  _Nullable x) {
            NSLog(@"%@",x);
        }];
    }];
    
    
    [subjectOfSignal sendNext:subject1];
    
    [subject1 sendNext:@"弄啥嘞"];



第二种:订阅最新的信号

    RACSubject * subjectOfSignal = [RACSubject subject];
    
    RACSubject * subject1 = [RACSubject subject];
    
    [subjectOfSignal.switchToLatest subscribeNext:^(id  _Nullable x) {
        NSLog(@"%@",x);
    }];
    
    [subjectOfSignal sendNext:subject1];
    
    [subject1 sendNext:@"弄啥嘞"];



现在又多一种:

    RACSubject * subjectOfSignal = [RACSubject subject];
    
    RACSubject * subject1 = [RACSubject subject];
    
    [[subjectOfSignal flattenMap:^__kindof RACSignal * _Nullable(id  _Nullable value) {
        return value;
    }] subscribeNext:^(id  _Nullable x) {
        NSLog(@"%@",x);
    }];
    
    [subjectOfSignal sendNext:subject1];
    
    [subject1 sendNext:@"弄啥嘞"];
显示全文