duemunk / Async

Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch
MIT License
4.59k stars 316 forks source link

Add AsyncGroup struct to handle execution of groups of multiple dispatch blocks. #75

Closed eneko closed 8 years ago

eneko commented 8 years ago

AsyncGroup

AsyncGroup facilitates working with groups of asynchronous blocks.

Multiple dispatch blocks with GCD:

let group = AsyncGroup()
group.background {
    // Run on background queue
}
group.utility {
    // Run on utility queue, in parallel to the previous block
}
group.wait()

All modern queue classes:

group.main {}
group.userInteractive {}
group.userInitiated {}
group.utility {}
group.background {}

Custom queues:

let customQueue = dispatch_queue_create("Label", DISPATCH_QUEUE_CONCURRENT)
group.customQueue(customQueue) {}

Wait for group to finish:

let group = AsyncGroup()
group.background {
    // Do stuff
}
group.background {
    // Do other stuff in parallel
}
// Wait for both to finish
group.wait()
// Do rest of stuff

Custom asynchronous operations:

let group = AsyncGroup()
group.enter()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // Do stuff
    group.leave()
}
group.enter()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // Do other stuff in parallel
    group.leave()
}
// Wait for both to finish
group.wait()
// Do rest of stuff
duemunk commented 8 years ago

Looks really great :100:

Sorry for not looking at it sooner :/

100mango commented 8 years ago

@eneko @duemunk Would it be better if it support notify?

simply add

  public func notify(queue: dispatch_queue_t = GCD.mainQueue(), block: dispatch_block_t){
        dispatch_group_notify(group, queue, block)
    }

turn

dispatch_group_t group = dispatch_group_create();

dispatch_group_enter(group);
// do something async
{
 dispatch_group_leave(group);
}

dispatch_group_enter(group);
//do something async
{
        dispatch_group_leave(group);
}

dispatch_group_notify(group, dispatch_get_main_queue()) {
};

into this

let group = AsyncGroup()
group.background {
    // Run on background queue
}
group.utility {
    // Run on utility queue, in parallel to the previous block
}
group.notify{
//Run on main queue
}

82

eneko commented 8 years ago

I like it. It will be a great non-blocking alternative to group.wait.

100mango commented 8 years ago

Thanks, eneko. I will try my best to enhance the documentation.