如何订阅完成RACCommand

时间:2018-01-05 08:11:53

标签: ios reactive-cocoa

RACSignal *s1 = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{   
        NSLog(@"s1");
        [subscriber sendCompleted];
    });
    return nil;
}];
RACSignal *s2 = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        NSLog(@"s2");
        [subscriber sendCompleted];
    });
    return nil;
}];

self.command = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
    return [s1 then:^RACSignal * _Nonnull{
        return s2;
    }];
}];
[self.command execute:nil];
[self.command.executionSignals subscribeCompleted:^{
    NSLog(@"completed");
}];

我发现completed没有执行。如何使它工作?

1 个答案:

答案 0 :(得分:0)

RACCommand.executionSignals是一个属于RACCommand实例的信号。

在此信号上,该命令将为每次执行命令发送另一个RACSignal值。

使用您的代码段

[self.command.executionSignals subscribeCompleted:^{
    NSLog(@"Command was deallocated");
}];

您正在观察命令的RACSignal<RACSignal> - 只有在RACSignal被解除分配时,此信号才会完成。

如果您确实需要遵守该命令,则需要执行以下操作:

[self.command.executionSignals subscribeNext:^(RACSignal *innerSignal) {
    [innerSignal subscribeCompleted:^{
        NSLog(@"One execution of the command completed");
    }];
}];

subscribeNext的每个execute都会调用此RACCommandinnerSignal是您要观察的信号。

但是,如果您确实想知道单个执行何时完成,您可以直接订阅execute调用返回的信号:

[[self.command execute:nil] subscribeCompleted:^{
    NSLog(@"This execution of the command completed");
}];