I am trying to build a subclass of an AFHttpClient that uses ReactiveCocoa to access a paginated/cursored API endpoint. I want to create a signal that will fetch each page in turn and feed the received ids to its subscribers. this is my current implementation, I was wondering if this is the right way to do such thing or is there a more 'Reactive…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (RACSignal*)friendsId | |
{ | |
RACReplaySubject* subject = [RACReplaySubject subject]; | |
[self enqueueWithSubject:subject cursor:-1]; | |
return subject; | |
} | |
- (void)enqueueWithSubject:(RACSubject*)subject cursor:(NSInteger)cursor | |
{ | |
RACSignal* json = [self friendsIdAtCursor:cursor]; | |
@weakify(self); | |
[json subscribeNext:^(id json) { | |
@strongify(self); | |
[subject sendNext:json[@"ids"]]; | |
NSNumber* nextCursor = json[@"next_cursor"]; | |
if (!nextCursor || [nextCursor isEqual:@0]) { | |
[subject sendCompleted]; | |
} else { | |
[self enqueueWithSubject:subject cursor:[nextCursor integerValue]]; | |
} | |
} error:^(NSError *error) { | |
[subject sendError:error]; | |
}]; | |
} | |
- (RACSignal*)idsAtCursor:(NSInteger)cursor | |
{ | |
RACReplaySubject* subject = [RACReplaySubject subject]; | |
NSDictionary* parameters = @{ @"cursor" : [NSString stringWithFormat:@"%d",cursor] }; | |
NSURLRequest* request = [self requestWithMethod:@"GET" path:@"/ids.json" parameters:@{@"cursor" : @(cursor)}]; | |
AFHTTPRequestOperation* operation = [self HTTPRequestOperationWithRequest:request | |
success: | |
^(AFHTTPRequestOperation *operation, id json) | |
{ | |
[subject sendNext:json]; | |
[subject sendCompleted]; | |
} | |
failure: | |
^(AFHTTPRequestOperation *operation, NSError *error) | |
{ | |
[subject sendError:error]; | |
}]; | |
[self enqueueHTTPRequestOperation:operation]; | |
return subject; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment