RAC组合

2018-01-04  本文已影响0人  幻梦_

concat 组合

//信号A
    RACSignal *signalA = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        NSLog(@"请求A数据");
        [subscriber sendNext:@"AAA"];
        [subscriber sendCompleted];//第一个信号必须调用sendCompleted
        return nil;
    }];
    
    //信号B
    RACSignal *signalB = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        NSLog(@"请求B数据");
        [subscriber sendNext:@"BBB"];
        return nil;
    }];
    //按顺序执行信号先执行A,再执行B
    [[signalA concat:signalB] subscribeNext:^(id x) {
        //既能拿到A信号的值,又能拿到B信号的值
        NSLog(@"%@",x);
    }];

then

    //忽略A 拿到B的数据
    [[signalA then:^RACSignal * _Nonnull{
       //返回信号就是需要组合的信号
        return signalB;
    }] subscribeNext:^(id  _Nullable x) {
        NSLog(@"%@",x);
    }];

merge

RACSubject *subjectA = [RACSubject subject];
    RACSubject *subjectB = [RACSubject subject];
    RACSignal *mergeSignal = [subjectA merge:subjectB];
    [mergeSignal subscribeNext:^(id x) {
        //任意一个信号发送内容都回来到这个block
        NSLog(@"%@",x);
    }];
    [subjectB sendNext:@"B"];
    [subjectA sendNext:@"A"];

zipWith

RACSubject *subjectA = [RACSubject subject];
    RACSubject *subjectB = [RACSubject subject];
    //压缩成一个信号
    //zipWith:当一个界面有多个请求的时候,要等所有请求完成才能更新UI
    RACSignal *zipSignal = [subjectA zipWith:subjectB];
    [zipSignal subscribeNext:^(id x) {
        //x 是元祖类型
        NSLog(@"%@",x);
    }];
    [subjectA sendNext:@"1"];
    [subjectB sendNext:@"2"];

combineLatest

    //创建信号A
    RACSubject*signalA = [RACSubject subject];
    //创建信号B
    RACSubject*signalB = [RACSubject subject];
    [[RACSignal combineLatest:@[signalA,signalB]]subscribeNext:^(RACTuple * _Nullable x) {
        NSLog(@"%@",x);
    }];
    [signalA sendNext:@"A"];
    [signalB sendNext:@"B"];

reduce聚合

    //创建信号A
    RACSubject*signalA = [RACSubject subject];
    //创建信号B
    RACSubject*signalB = [RACSubject subject];
    [[RACSignal combineLatest:@[signalA,signalB] reduce:^id _Nullable(NSString *username,NSString *pwd){
        //处理数据
        return [NSString stringWithFormat:@"reduce--%@--%@",username,pwd];
    }]subscribeNext:^(id  _Nullable x) {
        NSLog(@"reduce--%@",x);
    }];
    [signalA sendNext:@"A"];
    [signalB sendNext:@"B"];
上一篇下一篇

猜你喜欢

热点阅读