Skip to content

Instantly share code, notes, and snippets.

@jspahrsummers
Forked from juliengrimault/gist:4953436
Last active December 13, 2015 18:19
Show Gist options
  • Save jspahrsummers/4954655 to your computer and use it in GitHub Desktop.
Save jspahrsummers/4954655 to your computer and use it in GitHub Desktop.
- (RACSignal*)friendsId
{
return [self enqueueWithCursor:-1];
}
- (RACSignal*)enqueueWithCursor:(NSInteger)cursor
{
@weakify(self);
return [[self idsAtCursor:cursor]
// Map each `next` (there should only be one) to a new signal.
flattenMap:^(id json) {
@strongify(self);
// Prepare a signal representing the next page of results.
NSNumber* nextCursor = json[@"next_cursor"];
RACSignal* nextRequest = [RACSignal empty];
if (nextCursor && ![nextCursor isEqual:@0]) {
nextRequest = [self enqueueWithCursor:[nextCursor integerValue]];
}
// Concatenate the results of this page with whatever comes from the
// next page.
return [[RACSignal return:json] concat:nextRequest];
}];
}
- (RACSignal*)idsAtCursor:(NSInteger)cursor
{
NSDictionary* parameters = @{ @"cursor" : [NSString stringWithFormat:@"%d",cursor] };
NSURLRequest* request = [self requestWithMethod:@"GET" path:@"/ids.json" parameters:@{@"cursor" : @(cursor)}];
@weakify(self);
// Using this method instead of a subject ensures that we don't start the
// request until someone subscribes to the result.
RACSignal *requestSignal = [RACSignal createSignal:^(id<RACSubscriber> subscriber) {
@strongify(self);
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];
}];
// Kicks off this request only when subscribed to, and makes sure that
// a RACReplaySubject is used to buffer values.
return [requestSignal replayLazily];
}
@juliengrimault
Copy link

I think you forgot to return a RACDisposable when creating the signal in idsAtCursor:

...
    [self enqueueHTTPRequestOperation:operation];
    return [RACDisposable disposableWithBlock:^{
            [operation cancel];
    }];
}];
// Kicks off this request only when subscribed to, and makes sure that
// a RACReplaySubject is used to buffer values.
return [requestSignal replayLazily];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment