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

StackOverflow https://stackoverflow.com/questions/21888356

  •  13-10-2022
  •  | 
  •  

Pregunta

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?

¿Fue útil?

Solución

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);
    }];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top