- (void)fetchAllFeeds {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.tableView.tableHeaderView = self.tbHeaderView;
self.fetchingCount = 0;
@weakify(self);
[[[[[[SMNetManager shareInstance] fetchAllFeedWithModelArray:self.feeds] map:^id(NSNumber *value) {
@strongify(self);
NSUInteger index = [value integerValue];
self.feeds[index] = [SMNetManager shareInstance].feeds[index];
return self.feeds[index];
}] doCompleted:^{
@strongify(self);
NSLog(@"fetch complete");
self.tbHeaderLabel.text = @"";
self.tableView.tableHeaderView = [[UIView alloc] init];
self.fetchingCount = 0;
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(SMFeedModel *feedModel) {
@strongify(self);
self.fetchingCount += 1;
self.tbHeaderLabel.text = [NSString stringWithFormat:@"正在获取%@...(%lu/%lu)",feedModel.title,(unsigned long)self.fetchingCount,(unsigned long)self.feeds.count];
[self.tableView reloadData];
}];
}
- (RACSignal *)fetchAllFeedWithModelArray:(NSMutableArray *)modelArray {
@weakify(self);
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
@strongify(self);
dispatch_queue_t fetchFeedQueue = dispatch_queue_create("com.starming.fetchfeed.fetchfeed", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
self.feeds = modelArray;
for (int i = 0; i < modelArray.count; i++) {
dispatch_group_enter(group);
SMFeedModel *feedModel = modelArray[i];
dispatch_async(fetchFeedQueue, ^{
[self GET:feedModel.feedUrl parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
self.feeds[i] = [self.feedStore updateFeedModelWithData:responseObject preModel:feedModel];
SMDB *db = [[SMDB alloc] init];
[[db insertWithFeedModel:self.feeds[i]] subscribeNext:^(NSNumber *x) {
SMFeedModel *model = (SMFeedModel *)self.feeds[i];
model.fid = [x integerValue];
[subscriber sendNext:@(i)];
dispatch_group_leave(group);
}];
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
dispatch_group_leave(group);
}];
});
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
[subscriber sendCompleted];
});
return nil;
}];
}