Skip to content

Instantly share code, notes, and snippets.

@kuhnroyal
Created March 25, 2014 12:09
Show Gist options
  • Select an option

  • Save kuhnroyal/9760542 to your computer and use it in GitHub Desktop.

Select an option

Save kuhnroyal/9760542 to your computer and use it in GitHub Desktop.
Example usage of ReactiveCocoa in a ViewModel for a UITableView(Controller) holding data in a mutable array with a command to load and reload data.
#import <Objection/Objection.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
#import <ReactiveCocoa/RACEXTScope.h>
#import "TableDataViewModel.h"
#import "RestApiConnector.h"
const NSUInteger kPageSize = 30;
@interface TableDataViewModel ()
@property(nonatomic, readonly) RestApiConnector *rest;
@property(nonatomic) NSMutableArray *data;
@property(nonatomic) RACCommand *loadCommand;
@end
@implementation TableDataViewModel
objection_requires_sel(@selector(rest))
- (id)init {
self = [super init];
if (self) {
[self configureLoadCommand];
[self configureActiveSignal];
}
return self;
}
- (void)configureActiveSignal {
@weakify(self);
RACSignal *dBA = [[self.didBecomeActiveSignal filter:^BOOL(id value) {
@strongify(self);
return self.data == nil;
}] mapReplace:@TRUE];
[self.loadCommand rac_liftSelector:@selector(execute:) withSignals:dBA, nil];
}
- (void)configureLoadCommand {
@weakify(self);
self.loadCommand = [[RACCommand alloc] initWithSignalBlock:^(NSNumber *reload) {
@strongify(self);
return [[self.rest getDataForPage:reload ? 0 : self.data.count / kPageSize size:kPageSize] map:^id(id value) {
return RACTuplePack_(reload, value);
}];
}];
self.loadCommand.allowsConcurrentExecution = FALSE;
RAC(self, data) = [[self.loadCommand.executionSignals flatten] reduceEach:^NSMutableArray *(NSNumber *reload, NSArray *data) {
@strongify(self);
if ([reload boolValue]) {
return [data mutableCopy];
} else {
NSMutableArray *array = [self.data mutableCopy];
[array addObjectsFromArray:data];
return array;
}
}];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment