ReactiveCocoa-冷热信号的创建

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

RACSignal
//冷信号
    RACSignal * signal = [RACSignal createSignal:^RACDisposable *(id 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 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-冷热信号的创建)