Skip to content

Instantly share code, notes, and snippets.

@hhanesand
Created March 27, 2015 02:28
Show Gist options
  • Save hhanesand/3747430b18d12c94fffe to your computer and use it in GitHub Desktop.
Save hhanesand/3747430b18d12c94fffe to your computer and use it in GitHub Desktop.
PFQueryTableViewController subclass
@implementation GLQueryTableViewController
- (instancetype)initWithStyle:(UITableViewStyle)style localDatastoreTag:(NSString *)tag {
self.localDatastoreTag = tag;
return [self initWithStyle:style className:nil];
}
- (void)loadObjects:(NSInteger)page clear:(BOOL)clear {
NSAssert(!self.paginationEnabled, @"GLQueryTableViewController can not be used with pagination enabled.");
self.loading = YES;
[self objectsWillLoad];
PFQuery *cacheQuery = [self queryForTable];
[cacheQuery fromPinWithName:self.localDatastoreTag];
RACSignal *cacheSignal = [cacheQuery findObjectsInbackgroundWithRACSignal];
PFQuery *netQuery = [self queryForTable];
RACSignal *netSignal = [netQuery findObjectsInbackgroundWithRACSignal];
@weakify(self);
[[[[[cacheSignal doNext:^(NSArray *cacheResponse) {
if ([cacheResponse count] > 0) {
@strongify(self);
[self updateInternalObjectsWithArray:cacheResponse clear:clear];
[self.tableView reloadData];
[self objectsDidLoad:nil];
}
}] combineLatestWith:netSignal] filter:^BOOL(RACTuple *tuple) {
@strongify(self);
[self.refreshControl endRefreshing];
return [self shouldUpdateTableViewWithCacheResponse:tuple.first andNetworkResponse:tuple.second];
}] reduceEach:^NSArray *(NSArray *cacheResponse, NSArray *networkResponse) {
return networkResponse;
}] subscribeNext:^(NSArray *objects) {
@strongify(self);
[self updateInternalObjectsWithArray:objects clear:YES];
[self updateLocalDatastoreWithObjects:objects];
[self objectsDidLoad:nil];
[self.tableView reloadData];
}];
}
- (BOOL)shouldUpdateTableViewWithCacheResponse:(NSArray *)cacheResponse andNetworkResponse:(NSArray *)networkResponse {
if ([cacheResponse isEqualToArray:networkResponse]) {
return NO;
}
if ([cacheResponse count] > [networkResponse count]) {
for (NSUInteger i = [networkResponse count]; i < [cacheResponse count]; i++) {
if (((PFObject *)cacheResponse[i]).objectId) {
return YES;
}
}
return NO;
}
return YES;
}
- (void)updateLocalDatastoreWithObjects:(NSArray *)array {
NSAssert(self.localDatastoreTag, @"Local datastore tag must be defined");
RACSignal *unpinSignal = [[PFObject unpinAllWithSignalAndName:self.localDatastoreTag] catch:^RACSignal *(NSError *error) {
return [RACSignal empty];
}];
if ([array count] > 0) {
unpinSignal = [unpinSignal concat:[PFObject pinAll:array withSignalAndName:self.localDatastoreTag]];
}
[unpinSignal subscribeCompleted:^{
NSLog(@"Done");
}];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment