ProductPromotion
Logo

Swift

made by https://0x3d.site

GitHub - duemunk/Async: Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch
Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch - duemunk/Async
Visit Site

GitHub - duemunk/Async: Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch

GitHub - duemunk/Async: Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch

This project is no longer maintained.

Async

Carthage compatible CocoaPods compatible

Now more than syntactic sugar for asynchronous dispatches in Grand Central Dispatch (GCD) in Swift

Async sugar looks like this:

Async.userInitiated {
	10
}.background {
	"Score: \($0)"
}.main {
	label.text = $0
}

So even though GCD has nice-ish syntax as of Swift 3.0, compare the above with:

DispatchQueue.global(qos: .userInitiated).async {
	let value = 10
	DispatchQueue.global(qos: .background).async {
		let text = "Score: \(value)"
		DispatchQueue.main.async {
			label.text = text
		}
	}
}

AsyncGroup sugar looks like this:

let group = AsyncGroup()
group.background {
    print("This is run on the background queue")
}
group.background {
    print("This is also run on the background queue in parallel")
}
group.wait()
print("Both asynchronous blocks are complete")

Install

Swift Package Manager

Add To Your Project In Xcode 11:

File > Swift Packages > Add Package Dependency

Add As A Dependency In Package.swift:
dependencies: [
    .package(url: "https://github.com/duemunk/Async", from: "2.1.0"),
],

CocoaPods

use_frameworks!
pod "AsyncSwift"

Carthage

github "duemunk/Async"

Benefits

  1. Avoid code indentation by chaining
  2. Arguments and return types reduce polluted scopes

Things you can do

Supports the modern queue classes:

Async.main {}
Async.userInteractive {}
Async.userInitiated {}
Async.utility {}
Async.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 {
	print("This is run on the background queue")
}

// Run other code here...

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

Custom queues:

let customQueue = DispatchQueue(label: "CustomQueueLabel", attributes: [.concurrent])
let otherCustomQueue = DispatchQueue(label: "OtherCustomQueueLabel")
Async.custom(queue: customQueue) {
	print("Custom queue")
}.custom(queue: otherCustomQueue) {
	print("Other custom queue")
}

Dispatch block after delay:

let seconds = 0.5
Async.main(after: seconds) {
	print("Is called after 0.5 seconds")
}.background(after: 0.4) {
	print("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 {
		print("A \(i)")
	}
}
let block2 = block1.background {
	print("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
}

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

The way it work is by using the new notification API for GCD introduced in OS X 10.10 and iOS 8. Each chaining block is called when the previous queue has finished.

let previousBlock = {}
let chainingBlock = {}
let dispatchQueueForChainingBlock = ...

// Use the GCD API to extend the blocks
let _previousBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, previousBlock)
let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock)

// Use the GCD API to call back when finishing the "previous" block
dispatch_block_notify(_previousBlock, dispatchQueueForChainingBlock, _chainingBlock)

The syntax part of the chaining works by having class methods on the Async object e.g. Async.main {} which returns a struct. The struct has matching methods e.g. theStruct.main {}.

Known bugs

Modern GCD queues don't work as expected in the iOS Simulator. See issues 13, 22.

Known improvements

The dispatch_block_t can't be extended. Workaround used: Wrap dispatch_block_t in a struct that takes the block as a property.

Apply

There is also a wrapper for dispatch_apply() for quick parallelisation of a for loop.

Apply.background(100) { i in
	// Do stuff e.g. print(i)
}

Note that this function returns after the block has been run all 100 times i.e. it is not asynchronous. For asynchronous behaviour, wrap it in a an Async block like Async.background { Apply.background(100) { ... } }.

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.custom(queue: 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

License

The MIT License (MIT)

Copyright (c) 2016 Tobias Due Munk

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.

More Resources
to explore the angular.

mail [email protected] to add your project or resources here 🔥.

Related Articles
to learn about angular.

FAQ's
to learn more about Angular JS.

mail [email protected] to add more queries here 🔍.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory