Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I subscribe to the completion of a command's execution signals without a nested subscription?

I tried the following without success. The equivalent using -subscribeNext: works as expected.

// A
[[_viewModel.loginCommand.executionSignals flatten] subscribeCompleted:^{
    NSLog(@"A");
}];

My only working implementation is as follows:

// B
[_viewModel.loginCommand.executionSignals subscribeNext:^(RACSignal *loginSignal) {
    [loginSignal subscribeCompleted:^{
        NSLog(@"B");
    }];
}];

Why doesn't -flatten work in "A", and how I can I rewrite "B" to not use a nested subscription?

like image 361
Paul Young Avatar asked Mar 13 '14 00:03

Paul Young


1 Answers

The -flatten operator returns a signal that completes only when all of the inner signals have completed, which requires the outer signal to complete as well. The same is true of -concat. Because of this, once you apply either operator, the resulting signal has no representation of individual completion, only the final aggregate completion.

Alternative to nested subscriptions, you could transform the inner signals so that they send a value that signifies completion. One way of doing this is with -materialize:

[[[_viewModel.loginCommand.executionSignals
    map:^(RACSignal *loginSignal) {
        // Using -ignoreValues ensures only the completion event is sent.
        return [[loginSignal ignoreValues] materialize];
    }]
    concat]
    subscribeNext:^(RACEvent *event) {
        NSLog(@"Completed: %@", event);
    }];

Note that I used -concat instead of -flatten, since it matches the semantics of RACCommand's default serial execution. They ultimately do the same in this case, -flatten degenerates to the behavior of -concat because the command only executes signals one at a time.

Using -materialize isn't the only way to do this, it just happens to send a value that represents completion, but that could be any value that you find appropriately significant for your use case.

like image 129
Dave Lee Avatar answered Oct 01 '22 08:10

Dave Lee