7ynk3r
7ynk3r

Reputation: 1008

RACSignal map with error

I have a simple question but I can't find a nice solution to it.

I have a signal that sends strings, and a map after it. The map converts the strings into JSON.

It may happen that the string has a wrong format and the JSON parser will fail to parse with an error.

[stringGeneratorSignal map:^(NSString *bussinessObjectString){
    NSError *error;
    BussinessObject *obj = [[BussinessObject alloc] initWithString:bussinessObjectString error:&error];
    if (error) {
        NSLog(@"%@", error);
    }
    return obj;
}];

But because I'm inside the map I can't return an error signal. What I would like is to get an error with the error provided by the parser.

A couple of possibilities I've analyzed that I don't like:

What is the best approach for this kind of scenarios?

Thanks!

Upvotes: 1

Views: 512

Answers (1)

Chris Morse
Chris Morse

Reputation: 334

Look at -tryMap. It allows you to return data or nil and then set the error

/// Runs `mapBlock` against each of the receiver's values, mapping values until
/// `mapBlock` returns nil, or the receiver completes.
///
/// mapBlock - An action to map each of the receiver's values. The block should
///            return a non-nil value to indicate that the action was successful.
///            This block must not be nil.
///
/// Example:
///
///   // The returned signal will send an error if data cannot be read from
///   // `fileURL`.
///   [signal tryMap:^(NSURL *fileURL, NSError **errorPtr) {
///       return [NSData dataWithContentsOfURL:fileURL options:0 error:errorPtr];
///   }];
///
/// Returns a signal which transforms all the values of the receiver. If
/// `mapBlock` returns nil for any value, the returned signal will error using
/// the `NSError` passed out from the block.
- (RACSignal *)tryMap:(id (^)(id value, NSError **errorPtr))mapBlock;

Upvotes: 2

Related Questions