Search code examples
objective-creactive-cocoa

Objective-C ReactiveCocoa fold (aggregate)


I have next code

RACSubject *subject = [RACSubject subject];

[subject subscribeNext:^(id x) {
    NSLog(@"A: %@", x);
}];

[[subject aggregateWithStart:@"" reduce:^id(NSString *running, NSString *next) {
    return [running stringByAppendingString:next];
}] subscribeNext:^(id x) {
    NSLog(@"B: %@", x);
}];

[subject sendNext:@"hello"];
[subject sendNext:@"world"];

but

subscribeNext:^(id x) {
    NSLog(@"B: %@", x);
}

don't call, why? and how to fix it?

current log:

2016-01-05 02:11:39.472 xxx[38643:7565618] A: hello
2016-01-05 02:11:39.472 xxx[38643:7565618] A: world

waiting log:

A: hello
A: world
B: hello world

p.s. ReactiveCocoa 2.5


Solution

  • From the documentation for aggregateWithStart:reduce:

    Returns a signal that will send the aggregated value when the receiver completes, then itself complete.

    The key is that the receiver needs to complete in order for the aggregate to "finish" and send its value along. So you need a [subject sendCompleted]; statement.

    If this isn't the behavior you want, there's a related method called combinePreviousWithStart:reduce: that will give you output like this:

    A: hello
    B: hello
    A: world
    B: helloworld