Search code examples
iosvalidationtableviewreactive-cocoa

View validations using ReactiveCocoa


I have a tableview with custom cell containing 4 textfields and a button UPDATE. I show the data coming from web service in tableview. When the any one of the textfields is empty, UPDATE button should be hidden.

MODEL has the following properties to be mapped with the 4 textfields in each cell

@interface ClaimRequestModel : JSONModel 

@property (strong, atomic) NSString <Optional> *id;
@property (strong, atomic) NSString <Optional> *trip_id;
@property (strong, atomic) NSString <Optional> *item;
@property (strong, atomic) NSString <Optional> *name;
@property (strong, nonatomic) NSString <Optional> *description;
@end

I have tried to create RACSignal on property "name" in the TableViewController as

- (void)viewDidLoad {
   [savedClaims enumerateObjectsUsingBlock:^(ClaimRequestModel *claim, NSUInteger idx, BOOL * _Nonnull stop) {
            [claimSignals addObject:RACObserve(claim, name)];
    }];
     enableCostSignal = [RACSignal combineLatest:costSignals];
    [self setupClaimTypeSignal:[RACSignal combineLatest:claimSignals]];
//        [self.tableView reloadData];

}
-(void)setupClaimTypeSignal:(RACSignal*) signal {
    [[signal map:^id(RACTuple *values) {
        for (NSString *string in values) {
            if ([string isEmpty]) {
                return @(NO);
            }
        }
        return @(YES);
    }] subscribeNext:^(id x) {
        self.validInput = [x boolValue];
    }];

}

It works fine with one property "name" and I would like to observe all the properties in the ClaimRequestModel.

Do I need to create multiple signal arrays for each property? if so, what if the model has more than 15 properties?

Could any one please help me in the best practice using ReactiveCocoa?


Solution

  • May be you need to add signal in cellForRowAtIndexPath to check the condition.

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
       ClaimRequestCell *cell = [[[UINib nibWithNibName:@"ClaimRequestCell" bundle:nil] instantiateWithOwner:nil options:nil] firstObject];
    
       cell = [tableView dequeueReusableCellWithIdentifier:cell.reuseIdentifier];
    
       ClaimRequestModel *claim = [savedClaims objectAtIndex:indexPath.row];
    
       RACSignal *valid = [RACSignal
                        combineLatest:@[[RACObserve(claim, name) ignore:nil], [RACObserve(claim, item) ignore:nil],[RACObserve(claim, trip_id) ignore:nil] ]
                        reduce:^(NSString *name, NSString *item, NSString *trip_id ) {
                            return @([name length] == 0 && [item length] == 0 && [trip_id length] == 0);
                        }];
    
       RAC(cell.updateButton, enabled) = valid;
    
       return cell;
    }
    

    Hope this will help you.