Paul Young
Paul Young

Reputation: 1477

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?

Upvotes: 0

Views: 114

Answers (1)

Justin Spahr-Summers
Justin Spahr-Summers

Reputation: 16973

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);
    }];

Upvotes: 1

Related Questions