Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch (iOS7+ and OS X 10.9+ compatible)

Overview

Async.legacy

Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch (GCD)

Async rewritten for iOS7 and OS X 10.9 Compatibility. Unless you are targeting iOS7 or 10.9 I recommend you stick to the full Async for more features and possibly better performance. You will particularly benefit from the availability of the new QoS classes available in iOS8 and OS X 10.10 (Yosemite).

See this article about how it works.

Async sugar looks like this:

Async.background {
	println("This is run on the background queue")
}.main {
	println("This is run on the main queue, after the previous block")
}

Instead of the familiar syntax for GCD:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
	println("This is run on the background queue")
	
	dispatch_async(dispatch_get_main_queue(), 0), {
		println("This is run on the main queue, after the previous block")
	})
})

Installing

Just drop the AsyncLegacy.swift file into your project then you can make the calls as described in this document.

Benefits

  1. Less verbose code
  2. Less code indentation

Support

OS X 10.9+ and iOS 7+

Things you can do

Access different priority queues:

Async.main {}
Async.userInteractive {} // Remapped to DISPATCH_QUEUE_PRIORITY_HIGH
Async.userInitiated {}   // Remapped to DISPATCH_QUEUE_PRIORITY_HIGH
Async.default_ {}        // Remapped to DISPATCH_QUEUE_PRIORITY_DEFAULT 
Async.utility {}         // Remapped to DISPATCH_QUEUE_PRIORITY_LOW
Async.background {}      // Remapped to DISPATCH_QUEUE_PRIORITY_BACKGROUND

Chain as many blocks as you want:

Async.userInitiated {
	// 1
}.main {
	// 2
}.background {
	// 3
}.main {
	// 4
}

Store reference for later chaining:

let backgroundBlock = Async.background {
	println("This is run on the background queue")
}

// Run other code here...

// Chain to reference
backgroundBlock.main {
	println("This is run on the \(qos_class_self().description) (expected \(qos_class_main().description)), after the previous block")
}

Custom queues:

let customQueue = dispatch_queue_create("CustomQueueLabel", DISPATCH_QUEUE_CONCURRENT)
let otherCustomQueue = dispatch_queue_create("OtherCustomQueueLabel", DISPATCH_QUEUE_CONCURRENT)
Async.customQueue(customQueue) {
	println("Custom queue")
}.customQueue(otherCustomQueue) {
	println("Other custom queue")
}

Dispatch block after delay:

let seconds = 0.5
Async.main(after: seconds) {
	println("Is called after 0.5 seconds")
}.background(after: 0.4) {
	println("At least 0.4 seconds after previous block, and 0.9 after Async code is called")
}

Cancel blocks that aren't already dispatched:

// Cancel blocks not yet dispatched
let block1 = Async.background {
	// Heavy work
	for i in 0...1000 {
		println("A \(i)")
	}
}
let block2 = block1.background {
	println("B – shouldn't be reached, since cancelled")
}
Async.main { 
	// Cancel async to allow block1 to begin
	block1.cancel() // First block is _not_ cancelled
	block2.cancel() // Second block _is_ cancelled
}

Blocks chained to cancelled blocks WILL be run.

Wait for block to finish – an ease way to continue on current queue after background task:

let block = Async.background {
	// Do stuff
}

// Do other stuff

block.wait()

How does it work

It creates a dispatch group for each block and uses that to notify other blocks to run. In places blocks are wrapped in other blocks to explitly enter or leave groups so that following blocks are appropriately signalled.

See this article for more details or just review the code, it is fairly short. Get in touch if you have any questions.

The syntax part of the chaining works by having class methods on the Async object e.g. Async.main {} which returns an Async object. The object has matching methods e.g. theObject.main {}. Objects are used so that you can pass the the object by reference so that you can cancel it if required.

Known improvements

default is a keyword. Workaround used: default_. Could use this trick shown be Erica Sadun, i.e. class func `default`() -> {} but it results in this use Async.`default`{}

License

The MIT License (MIT)

Copyright (c) 2014 Tobias Due Munk Copyright (c) 2014 Joseph Lord (Human Friendly Ltd.)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You might also like...
Venice - Coroutines, structured concurrency and CSP for Swift on macOS and Linux.
Venice - Coroutines, structured concurrency and CSP for Swift on macOS and Linux.

Venice provides structured concurrency and CSP for Swift. Features Coroutines Coroutine cancelation Coroutine groups Channels Receive-only chan

Async and concurrent versions of Swift’s forEach, map, flatMap, and compactMap APIs.

CollectionConcurrencyKit Welcome to CollectionConcurrencyKit, a lightweight Swift package that adds asynchronous and concurrent versions of the standa

Slack message generator and API client, written in Swift with Result Builders and Concurrency

Slack Message Client This package provides a Swift object model for a Slack Block Kit message, as well as a Result Builder convenience interface for e

Automatically generate GraphQL queries and decode results into Swift objects, and also interact with arbitrary GitHub API endpoints

GitHub API and GraphQL Client This package provides a generic GitHub API client (GithubApiClient) as well as Codable-like GitHub GraphQL querying and

Make your logic flow and data flow clean and human readable

Flow What's Flow Flow is an utility/ design pattern that help developers to write simple and readable code. There are two main concerns: Flow of opera

Extensions and additions to AsyncSequence, AsyncStream and AsyncThrowingStream.

Asynchone Extensions and additions to AsyncSequence, AsyncStream and AsyncThrowingStream. Requirements iOS 15.0+ macOS 12.0+ Installation Swift Packag

straightforward networking and error handling with async-await and URLSession

AsyncAwaitNetworkingPlayground How To Run Just clone the project, open it and run. Some notes about AsyncAwaitNetworkingPlayground It's a straightforw

A complete set of primitives for concurrency and reactive programming on Swift
A complete set of primitives for concurrency and reactive programming on Swift

A complete set of primitives for concurrency and reactive programming on Swift 1.4.0 is the latest and greatest, but only for Swift 4.2 and 5.0 use 1.

SwiftCoroutine - Swift coroutines for iOS, macOS and Linux.
SwiftCoroutine - Swift coroutines for iOS, macOS and Linux.

Many languages, such as Kotlin, Go, JavaScript, Python, Rust, C#, C++ and others, already have coroutines support that makes the async/await pattern i

Comments
  • Arguments and returns - Not working! For discussion not merging.

    Arguments and returns - Not working! For discussion not merging.

    Note this is not something for merging currently but a non-functional discussion point based on @chriseidhof's suggestion in https://github.com/duemunk/Async/issues/8. This is very much Async.legacy code and could not be directly merged with Async itself.

    I've tried implementing chainable dispatches with arguments and return values being passed down the chain and I think I've defeated the Swift type system as the library compiles but I can't seem to actually call any of the functions.

    If Chris or anyone else can tell me what I'm doing wrong or if it really is Swift's fault I would really appreciate it.

    opened by josephlord 4
  • Upstream merge branch

    Upstream merge branch

    Merge upstream changes (translated as required). Just one Async class (cancel doesn't work if it is a schedule in the legacy version) rather than separate classes/structs with the return value and the static/class methods.

    Also modified the test to print less debug and fixed a cancel bug when chaining from cancelled methods.

    opened by josephlord 0
  • Enable cancel()

    Enable cancel()

    Enable cancelation by changing DispatchBlock to a class and keeping a state as to whether it is cancelled.

    Chained blocks get run as if the cancelled block completed as normal. Not sure yet if this matches Async behaviour. Will merge this when I have confirmed matching behaviour.

    opened by josephlord 0
  • GCD chained arguments and returns take2

    GCD chained arguments and returns take2

    @chriseidhof

    I've got strongly typed chained calls with arguments and return types working without any damage to the existing original API. (https://github.com/duemunk/Async/issues/8)

    Surprisingly (or maybe not to you) the someChainableAsyncObject.cancel() still works passing the correct type () into the function.

         func cancel(withValue:ReturnType) {
            isCancelled = true
            returnedValueOpt = withValue
        }
    

    By forcing the setting of the return on cancel it ensures that there is a non-Optional value to wait on (unless the block's type was optional to start with) and the chain can continue.

    It needs more syntactic sugar on the new API features (Beta 6 doesn't seem to like the closure after the call syntax for these flexibly typed closures) and arguments are required on AsyncPlus calls even if it is (). It also needs more tests, a cleanup and I need to think about the effect on the drop in replacement nature of this for the main Async library but I'm happy I've got this far.

    opened by josephlord 4
Owner
Joseph Lord
Joseph Lord
GCDTimer - Well tested Grand Central Dispatch (GCD) Timer in Swift

GCDTimer Well tested Grand Central Dispatch (GCD) Timer in Swift. Checkout the test file. Usage Long running timer import GCDTimer

Hemant Sapkota 183 Sep 9, 2022
Grand Central Dispatch simplified with swift.

GCDKit GCDKit is Grand Central Dispatch simplified with Swift. for Swift 1.2: Use version 1.0.1 for Swift 2.1 / 2.2: Use the master branch Introductio

John Estropia 317 Dec 6, 2022
A wrapper of Grand Central Dispatch written in Swift

GCD A wrapper of Grand Central Dispatch written in Swift. Examples gcd // submit your code for asynchronous execution on a global queue with high prio

Le Van Nghia 75 May 19, 2022
Chronos is a collection of useful Grand Central Dispatch utilities

Chronos is a collection of useful Grand Central Dispatch utilities. If you have any specific requests or ideas for new utilities, don't hesitate to create a new issue.

Comyar Zaheri 248 Sep 19, 2022
Queuer is a queue manager, built on top of OperationQueue and Dispatch (aka GCD).

Queuer is a queue manager, built on top of OperationQueue and Dispatch (aka GCD). It allows you to create any asynchronous and synchronous task easily, all managed by a queue, with just a few lines.

Fabrizio Brancati 1k Dec 2, 2022
GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way

GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way. This help

Quan Vo 42 Oct 5, 2022
iOS 13-compatible backports of commonly used async/await-based system APIs that are only available from iOS 15 by default.

AsyncCompatibilityKit Welcome to AsyncCompatibilityKit, a lightweight Swift package that adds iOS 13-compatible backports of commonly used async/await

John Sundell 367 Jan 5, 2023
Futures is a cross-platform framework for simplifying asynchronous programming, written in Swift.

Futures Futures is a cross-platform framework for simplifying asynchronous programming, written in Swift. It's lightweight, fast, and easy to understa

David Ask 60 Aug 11, 2022
AwaitKit is a powerful Swift library which provides a powerful way to write asynchronous code in a sequential manner.

AwaitKit is a powerful Swift library inspired by the Async/Await specification in ES8 (ECMAScript 2017) which provides a powerful way to write asynchronous code in a sequential manner.

Yannick Loriot 752 Dec 5, 2022
AsyncTimer is a precision asynchronous timer. You can also use it as a countdown timer

AsyncTimer ?? Features Can work as a countdown timer Can work as a periodic Timer Can work as a scheduled timer Working with user events (like: scroll

Adrian Bobrowski 26 Jan 1, 2023