Question

I have a signal A that contains integer values. A value of -1 indicates an invalid result, so I'd like to, instead of passing -1 along as a value, send an error. This way anything that subscribes to B will receive valid integers through subscribeNext: and the errors through subscribeError:.

I think I know how to do this with RACSubject:

RACSequence *A = [@[ @(2), @(6), @(5), @(-1), @(4) ] rac_sequence];
RACSubject *B = [RACSubject subject];
[A subscribeNext:^(NSNumber *val) {
    if ( [val integerValue] == -1 ) {
        [B sendError:[NSError errorWithDomain:@"MyDomain" code:0 userInfo:nil]];
    } else {
        [B sendNext:val];
    }
} error:^(NSError *error) {
    [B sendError:error];
} completed:^{
    [B sendCompleted];
}];

I'm wondering if there's a more "inline" way to do this along the lines of:

RACSequence *A = [@[ @(2), @(6), @(5), @(-1), @(4) ] rac_sequence];
RACSignal *B = [A filter:^BOOL(id val) {
    if ( [val integerValue] == -1 ) {
        //FIXME: send an error to B's subscriber(s)
        return NO;
    } else {
        return YES;
    }
}
Was it helpful?

Solution

The primary method to do this is by using -flattenMap:, similar to how you've written the -filter: above. Using your example:

RACSignal *B = [A flattenMap:^(NSNumber *number) {
    if (number.intValue == -1) {
        return [RACSignal error:[NSError errorWithDomain:@"MyDomain" code:0 userInfo:nil]];
    } else {
        return [RACSignal return:number];
    }
}];

Update

Alternatively, using the newer -try: operator:

RACSignal *B = [A try:^(NSNumber *number, NSError **error) {
    if (number.intValue == -1) {
        *error = [NSError errorWithDomain:@"MyDomain" code:0 userInfo:nil];
        return NO;
    }

    return YES;
}];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top