Search code examples
iosobjective-cruntimereactive-cocoa

How does filter method work?


-(instancetype)filter:(BOOL (^)(id value))block {
NSCParameterAssert(block != nil);

Class class = self.class;

return [[self flattenMap:^ id (id value) {
    if (block(value)) {
        return [class return:value];
    } else {
        return class.empty;
    }
}] setNameWithFormat:@"[%@] -filter:", self.name];

}

This is the implementation of filter of ReactiveCocoa.I don't know what this code means.Also I can't get any reference to the second return method.

 return [class return:value];

Also, what does this instancetype mean? Suppose the value is a string and I check whether its length is greater than 2. What will be returned by using filter method?


Solution

  • The filter method invokes the class method of the current class to get a RACStream subclass using that method. Using return: will give a signal that sends the value passed and then completes. Using empty gives a signal that immediately sends completed without sending a next value, which removes the value filtered value from the stream thanks to flattenMap: switching out the signal with the one being created.