Skip to content

Instantly share code, notes, and snippets.

@berkus
Created May 31, 2013 09:33
Show Gist options
  • Save berkus/5683901 to your computer and use it in GitHub Desktop.
Save berkus/5683901 to your computer and use it in GitHub Desktop.
//
// SWFHTTPClient
// RACCancelTest
//
// Created by Nikolay Kasyanov on 29.03.13.
// Copyright (c) 2013 Softwear Finance. All rights reserved.
//
#import "SWFHTTPClient.h"
@implementation SWFHTTPClient {
NSMutableDictionary *_activeSignals;
NSRecursiveLock *_lock;
}
- (instancetype)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (self != nil) {
_activeSignals = [NSMutableDictionary dictionary];
_lock = [NSRecursiveLock new];
}
return self;
}
- (RACSignal *)feedAtPath:(NSString *)path
{
NSParameterAssert(path != nil);
RACSignal *existingSignal;
[_lock lock];
existingSignal = _activeSignals[path];
if (existingSignal == nil) {
RACSignal *networkSignal = [[RACSignal createSignal:^RACDisposable *(id <RACSubscriber> subscriber) {
NSURLRequest *request = [self requestWithMethod:@"GET"
path:path
parameters:nil];
void (^success)(AFHTTPRequestOperation *, id) =
^(AFHTTPRequestOperation *operation, id responseObject) {
[subscriber sendNext:responseObject];
[subscriber sendCompleted];
};
void (^failure)(AFHTTPRequestOperation *, NSError *) =
^(AFHTTPRequestOperation *operation, NSError *error) {
[subscriber sendError:error];
};
AFHTTPRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:success
failure:failure];
[self enqueueHTTPRequestOperation:operation];
return [RACDisposable disposableWithBlock:^{
[operation cancel];
}];
}] finally:^{
[self removeSignalForPath:path];
}];
existingSignal = [[networkSignal multicast:[RACSubject subject]] autoconnect];
_activeSignals[path] = existingSignal;
}
[_lock unlock];
return existingSignal;
}
- (void)removeSignalForPath:(NSString *)path
{
NSParameterAssert(path != nil);
[_lock lock];
[_activeSignals removeObjectForKey:path];
[_lock unlock];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment