Refactor sender methods to enable testing of async code

This commit is contained in:
Christoph Wendt 2015-09-10 18:55:44 -07:00
parent e32c1e5c8b
commit 2bcd14d132

View File

@ -36,12 +36,18 @@ static NSUInteger const defaultRequestLimit = 10;
queue:nil queue:nil
usingBlock:^(NSNotification *notification) { usingBlock:^(NSNotification *notification) {
typeof(self) strongSelf = weakSelf; typeof(self) strongSelf = weakSelf;
[strongSelf sendSavedData]; [strongSelf sendSavedDataAsync];
}]; }];
} }
#pragma mark - Sending #pragma mark - Sending
- (void)sendSavedDataAsync{
dispatch_async(self.senderQueue, ^{
[self sendSavedData];
});
}
- (void)sendSavedData{ - (void)sendSavedData{
@synchronized(self){ @synchronized(self){
if(_runningRequestsCount < _maxRequestCount){ if(_runningRequestsCount < _maxRequestCount){
@ -50,13 +56,9 @@ static NSUInteger const defaultRequestLimit = 10;
return; return;
} }
} }
__weak typeof(self) weakSelf = self; NSString *path = [self.persistence requestNextPath];
dispatch_async(self.senderQueue, ^{ NSData *data = [self.persistence dataAtPath:path];
typeof(self) strongSelf = weakSelf; [self sendData:data withPath:path];
NSString *path = [self.persistence requestNextPath];
NSData *data = [self.persistence dataAtPath:path];
[strongSelf sendData:data withPath:path];
});
} }
- (void)sendData:(NSData * __nonnull)data withPath:(NSString * __nonnull)path { - (void)sendData:(NSData * __nonnull)data withPath:(NSString * __nonnull)path {
@ -87,7 +89,7 @@ static NSUInteger const defaultRequestLimit = 10;
NSInteger statusCode = httpResponse.statusCode; NSInteger statusCode = httpResponse.statusCode;
[strongSelf handleResponseWithStatusCode:statusCode responseData:data filePath:path error:error]; [strongSelf handleResponseWithStatusCode:statusCode responseData:data filePath:path error:error];
}]; }];
[task resume]; [self resumeSessionDataTask:task];
}else{ }else{
BITHTTPOperation *operation = [BITHTTPOperation operationWithRequest:request]; BITHTTPOperation *operation = [BITHTTPOperation operationWithRequest:request];
[operation setCompletion:^(BITHTTPOperation *operation, NSData *responseData, NSError *error) { [operation setCompletion:^(BITHTTPOperation *operation, NSData *responseData, NSError *error) {
@ -100,6 +102,10 @@ static NSUInteger const defaultRequestLimit = 10;
} }
} }
- (void)resumeSessionDataTask:(NSURLSessionDataTask *)sessionDataTask {
[sessionDataTask resume];
}
- (void)handleResponseWithStatusCode:(NSInteger)statusCode responseData:(NSData *)responseData filePath:(NSString *)filePath error:(NSError *)error{ - (void)handleResponseWithStatusCode:(NSInteger)statusCode responseData:(NSData *)responseData filePath:(NSString *)filePath error:(NSError *)error{
self.runningRequestsCount -= 1; self.runningRequestsCount -= 1;