Async

https://github.com/duemunk/Async

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

这是一个Swift中GCD的语法糖库。

Async sugar looks like this:

Async使用起来就像这样子:

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(), {
println("This is run on the main queue, after the previous block")
})
})

Install

pod 'Async', :git => 'https://github.com/duemunk/Async.git'

Benefits

  1. Less verbose code 更少的冗余代码
  2. Less code indentation 更少的缩进风

Things you can do

Supports the modern queue classes:

支持常用的queue类:

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

Chain as many blocks as you want:

你可以将不同的block链接起来使用:

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:

自定义queue:

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
}

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

等待一个block运行结束:

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.

本库使用了 iOS 8 提供的通知 API 来完成相关功能,每一个block都会在上一个block执行完了之后继续执行:

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 1322.

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.

Bonus stuff

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

Apply.background(100) { i in
// Do stuff e.g. println(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.main{ Apply.background(100) { ... } }.

[swift] Async的更多相关文章

  1. Awesome Swift

    Awesome Swift https://github.com/matteocrippa/awesome-swift A collaborative list of awesome Swift re ...

  2. Swift 的 pod 第三方库

    #HTTPpod 'Alamofire' #Elegant HTTP Networking in Swiftpod 'SwiftHTTP' #Thin wrapper around NSURLSess ...

  3. iOS的非常全的三方库,插件,大牛博客

    转自: http://www.cnblogs.com/zyjzyj/p/6015625.html github排名:https://github.com/trending, github搜索:http ...

  4. AWESOME SWIFT-swift.libhunt.com-swift类库网站

    https://swift.libhunt.com/categories/688-events 29 Events libraries and projects ORDERED BY POPULARI ...

  5. iOS -- 开源项目和库

    TimLiu-iOS 目录 UI 下拉刷新 模糊效果 AutoLayout 富文本 图表 表相关与Tabbar 隐藏与显示 HUD与Toast 对话框 其他UI 动画 侧滑与右滑返回手势 gif动画 ...

  6. ios很好的开源库

    Tim9Liu9/TimLiu-iOS 自己总结的iOS.mac开源项目及库,持续更新.. 目录 UI 下拉刷新 模糊效果 AutoLayout 富文本 图表 表相关与Tabbar 隐藏与显示 HUD ...

  7. app启动速度怎么提升?

    简介: APP 启动速度的重要性不言而喻.高德地图是一个有着上亿用户的超级 APP,本文从唤端技术.H5 启动页.下载速度.APP加载.线程调度和任务编排等方面,详解相关技术原理和实现方案,分享高德在 ...

  8. Swift 并行编程现状和展望 - async/await 和参与者模式

    这篇文章不是针对当前版本 Swift 3 的,而是对预计于 2018 年发布的 Swift 5 的一些特性的猜想.如果两年后我还记得这篇文章,可能会回来更新一波.在此之前,请当作一篇对现代语言并行编程 ...

  9. 【swift】BlockOperation和GCD实用代码块

    //BlockOperation // // ViewController.swift import UIKit class ViewController: UIViewController { @I ...

随机推荐

  1. 【Express系列】第3篇——接入mysql

    通常来说,前后端分离的项目,前端负责界面渲染和操作型的业务逻辑,后端则负责数据存取和数据处理相关的业务逻辑. 既然设计数据,那就少不了数据库的使用.目前市面上流行着各种各样的数据库,这里不打算一一列举 ...

  2. python单元测试pytest

    1.pytest简介 pytest是Python的一种单元测试框架,与python自带的unittest测试框架类似,但是比unittest框架使用起来更简洁,效率更高. 执行测试过程中可以将某些测试 ...

  3. 数据库应用(Mysql、Mongodb、Redis、Memcached、CouchDB、Cassandra)

    目前,主流数据库包括关系型(SQL)和非关系型(NoSQL)两种. 关系数据库是建立在关系模型基础上的数据库,借助于集合代数等数学概念和方法来处理数据库中的数据,支持复杂的事物处理和结构化查询.代表实 ...

  4. MySQL的各种join

    常用的是这5个join 首先join = inner join   这里有说明:点击打开链接 这里我就不用表来说明了,例子看这里 简单的说就是 inner join:不以谁为基准,只有符合关系的才会选 ...

  5. .Net Core全球化多语言

    参照:ASP.NET Core 全球化和本地化 步骤如下: 后台中的本地化. Startup.cs中注册服务并制定Resource文件的位置.注意:这里的位置不仅仅应用到Web层,如Infrastru ...

  6. TCP/IP协议栈概述及各层包头分析

    TCP/IP协议栈中各层包头的分析 Protocol列表示的是该数据包最高层对应的协议,Length列表示该包的长度(包括从底层的协议到最高层的协议,其中包头一般是,链路层14字节,IP20字节,TC ...

  7. MVC 基架不支持 Entity Framework 6 或更高版本 即 NuGet的几个小技巧

    MVC 基架不支持 Entity Framework 6 或更高版本.有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=276833. 原因:mvc版 ...

  8. springboot相关资料

    SpringBoot应用 rabbitmq先关资料: rabbitmq详解 springboot+rabbitmq整合示例程 RabbitMQ Exchange Queue RoutingKey Bi ...

  9. eclipse编译项目:Java @Override 注解报错的解决方法

    错误: 在 eclipse 的新工作空间开发项目时,出现大面积方法编译错误.鼠标放在方法名上后显示让我们去掉 @override 注解,如图: 原因: @Override 是 jdk5 引入的机制,但 ...

  10. Django(四):model

    一.创建model django.db.models是django自带的创建数据库的ORM. 在models.py中以继承models.Model创建表后,需要在setttngs中确保添加了当前应用, ...