美文网首页
ReactiveCocoa-冷热信号的创建

ReactiveCocoa-冷热信号的创建

作者: 我是繁星 | 来源:发表于2018-08-07 17:03 被阅读0次

    不了解冷热信号的看前一篇《ReactiveCocoa-冷信号和热信号的理解》
    RACSubject及其子类是热信号。
    RACSignal是冷信号。
    同时ReactiveCocoa还提供了API来将RACSignal转换为RACSubject。

    RACSignal
    //冷信号
        RACSignal * signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            NSLog(@"发送信号");
            [subscriber sendNext: @"1"];
            [subscriber sendNext:@"2"];
            [subscriber sendNext:@"3"];
            [subscriber sendCompleted];
            return nil;
        }];
        [signal subscribeNext:^(id x) {
            NSLog(@"sign1 :%@",x);
        }];
    
    RACSubject
        //热信号
        RACSubject * subject = [RACSubject subject];
        [subject subscribeNext:^(id x) {
    
        }];
        [subject sendNext:@"1"];
    

    RACSubject可以附加行为,例如RACReplaySubject,可以具备热信号特性,但是可以收到订阅之前发送的消息。

        RACReplaySubject * subject = [RACReplaySubject subject];
        [subject subscribeNext:^(id x) {
            
        }];
        [subject sendNext:@"1"];
    
    冷信号转换热信号
        RACMulticastConnection * connection = [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [[RACScheduler mainThreadScheduler] afterDelay:1 schedule:^{
                [subscriber sendNext: @"1"];
            }];
            [[RACScheduler mainThreadScheduler] afterDelay:2 schedule:^{
                [subscriber sendNext: @"2"];
            }];
            [[RACScheduler mainThreadScheduler] afterDelay:3 schedule:^{
                [subscriber sendNext: @"3"];
            }];
            [[RACScheduler mainThreadScheduler] afterDelay:4 schedule:^{
                [subscriber sendNext: @"4"];
            }];
            return nil;
        }] publish];
        [connection connect];
        RACSignal * signal = connection.signal;
        [signal subscribeNext:^(id x) {
              NSLog(@"sign1 :%@",x);
        }];
    

    相关文章

      网友评论

          本文标题:ReactiveCocoa-冷热信号的创建

          本文链接:https://www.haomeiwen.com/subject/cyeavftx.html