Search code examples
objective-creactive-cocoa

How can I subscribe to two signals and access their latest values without using nested subscriptions?


In my current situation I can get by with doing this:

[isFooSignal subscribeNext:^(NSNumber *isFoo) {
    [isBarSignal subscribeNext:^(NSNumber *isBar) {
        if ([isFoo boolValue]) {
            if ([isBar boolValue]){
                // isFoo and isBar are both true
            }
            else {
                // isFoo is true and isBar is false
            }
        }
    }];
}];

but ideally I think I want to subscribe to both signals and be able to access both of their latest values regardless of which changed first.

Something like:

...^(NSNumber *isFoo, NSNumber *isBar) {
    NSLog(@"isFoo: %@" isFoo);
    NSLog(@"isBar: %@", isBar);
}];

How can I achieve this using ReactiveCocoa?


Solution

  • You can do this with +combineLatest:reduce::

    [[RACSignal
        combineLatest:@[ isFooSignal, isBarSignal ]
        reduce:^(NSNumber *isFoo, NSNumber *isBar) {
            return @(isFoo.boolValue && isBar.boolValue);
        }]
        subscribeNext:^(NSNumber *isBoth) {
            NSLog(@"both true? %@", isBoth);
        }];