Search code examples
objective-ccocoareactive-cocoaraccommand

Cancel RACCommand execution


Is there any way to cancel execution of a RACCommand?

For example I have a command with infinite execution signal like this:

RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        __block BOOL stop = NO;

        while (!stop) {
            [subscriber sendNext:nil];
        }

        return [RACDisposable disposableWithBlock:^{
            stop = YES;
        }];
    }];
}];

So how can I stop it after calling [command execute:nil]?


Solution

  • I'm a bit new to RACCommand, so I'm not certain there's a better way to do this. But I have been using takeUntil: with a cancellation signal to halt execution.

    RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            while (true) {
                [subscriber sendNext:nil];
            }
        }] takeUntil:cancellationSignal];
    }];