Async
04 Dec 2015Async is a little, sharp focused library to help you write asynchronous code. At its core it is a wrapper around Grand Central Dispatch (GDC).
How to run code in the background with Async
A vanilla GDC background execution looks like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
// heavy code to be executed in the background
})
Whit async it looks like this:
Async.background {
// heavy code to be executed in the background
}
How to run code on the main thread with Async
Dispatching a closure to be executed on the main thread is equally simple and readable:
Async.main {
// code that should be executed on the main thread
}
So far you might not be very impressed by Async, but here’s when things get more interesting.
How to chain operations with Async
If you wanted to execute an expensive computation in the background and once that is done run a bit of code updating the UI on the main thread using vanilla GDC you would have to write something like:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
// execute expensive computation
dispatch_async(dispatch_get_main_queue(), {
// update UI
})
})
It is easy to see how this kind of code would degenerate in a callback hell when more than a couple of operations need to be executed in a certain order.
Async makes this easier:
Async.background {
// execute expensive computation
}
.main {
// update UI
}
Nice! Easier to read and easier to maintain in case you will need to change the order of execution, or add more at any point in the sequence.
Let me close with two other nice syntaxes that Async provides.
How to run code after a delay
Async.main(after: 2) {
// code to execute after 2 secondes on the main thread
}
How to cancel a dispatch that hasn’t started yet
You can store a reference to a scheduled Async
operation, and cancel it like this:
let operation = Async.background(after: 1) {
// ...
}
operation.cancel
Next Steps
Async is a little library, but it has more to offer. Head over to the project repo on GitHub to read more and browse the code. Also note that Async has a number of “enhancement” and “help wanted” tagged open issues, if you want to contribute that’s a great place to start. You can also checkout the usual example project with all the code from the tutorial and much more.
That’s it for today. See you tomorrow with a library that will get you rid of those horrific static table view in Interface Builder. Subscribe to the email list to avoid missing out.
If you found this post useful and want to support the Advent Calendar please consider sharing it on your favourite social network using the buttons below. Thanks 🎅