Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple block-based serial queue for asynchronous operations.
//
// QTMAsyncOperationQueue.h
// Quantum
//
// Created by Jonathan Willing on 10/28/13.
// Copyright (c) 2013 AppJon. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef void (^QTMAsyncOperationQueueCompletion)();
@interface QTMAsyncOperationQueue : NSObject
/// The queue on which the operations are dispatched.
///
/// Defaults to the main queue.
@property (nonatomic, assign) dispatch_queue_t dispatchQueue;
/// Adds an asynchronous operation to the queue. The operation will only be started when any
/// previously-enqueued operations have completed (serially).
///
/// The operations themselves be dispatched on `dispatchQueue`, which defaults to the main queue.
///
/// The completion block must be fired by the caller to signify the completion of the async operation.
- (void)addAsynchronousOperation:(void (^)(QTMAsyncOperationQueueCompletion completion))operation;
@end
//
// QTMAsyncOperationQueue.m
// Quantum
//
// Created by Jonathan Willing on 10/28/13.
// Copyright (c) 2013 AppJon. All rights reserved.
//
#import "QTMAsyncOperationQueue.h"
@interface QTMAsyncOperationQueue()
@property (nonatomic, strong) dispatch_group_t internalDispatchGroup;
@property (nonatomic, strong) dispatch_queue_t internalDispatchQueue;
@end
@implementation QTMAsyncOperationQueue
- (instancetype)init {
self = [super init];
if (self == nil) return nil;
self.dispatchQueue = dispatch_get_main_queue();
self.internalDispatchQueue = dispatch_queue_create("com.appjon.asyncOperationQueue", DISPATCH_QUEUE_SERIAL);
self.internalDispatchGroup = dispatch_group_create();
return self;
}
- (void)addAsynchronousOperation:(void (^)(QTMAsyncOperationQueueCompletion))operation {
dispatch_async(self.internalDispatchQueue, ^{
dispatch_group_enter(self.internalDispatchGroup);
void (^completion)() = ^{
dispatch_group_leave(self.internalDispatchGroup);
};
dispatch_async(self.dispatchQueue, ^{
operation(completion);
});
dispatch_group_wait(self.internalDispatchGroup, DISPATCH_TIME_FOREVER);
});
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.