swift-async
为异步控制流提供了一个通用的接口。它允许您将异步任务,如从网络加载数据或执行长时间运行的计算,与统一的完成处理程序组合在一起。
为了简单起见,考虑以下模型
class Room {
let number: Int
}
class Floor {
let name: String
}
class Building {
func performAsyncWork1(completionHandler: (NSError?) -> ()) {
// perform async work and invoke completionHandler when done
}
func fetchRoomsOnFloor(floor: Floor, completionHandler: ([Room]?, NSError?) -> ()) {
// fetch some data here and invoke completionHandler when done
}
func fetchFloors(completionHandler: ([Floor]?, NSError?) -> ()) {
// fetch some data here and invoke completionHandler when done
}
}
let building1 = Building()
let building2 = Building()
let tasks = [
Async.bind { building1.fetchFloors($0) },
Async.bind { building1.fetchRoomsOnFloor(Floor(name: "First floor"), $0) },
Async.bind { building2.fetchFloors($0) },
Async.bind { building2.fetchRoomsOnFloor(Floor(name: "First floor"), $0) },
]
Async.parallel(tasks) { (results, error) in
if let error = error {
println("Error: \(error)")
} else if let results = results {
let floors = results[0] as [Floor]
let rooms = results[1] as [Room]
println("Got floors: \(floors)")
println("And rooms: \(rooms)")
}
}
let building1 = Building()
let building2 = Building()
let tasks = [
building1.performAsyncWork1,
building2.performAsyncWork2,
Async.bind { building1.performAsyncWorkWithObject(nil, completionHandler: $0) },
]
Async.series(tasks) { (error) in
if let error = error {
return println("Error: \(error)")
} else {
println("all tasks succeeded")
}
}
所有函数都必须接收一个统一的完成处理程序,要么是接收
NSError?
参数T?
和一个 NSError?
参数swift-async
不是线程安全的,因此您需要确保所有完成处理程序都在同一个线程上执行。
swift-async 在一个 MIT 许可下发布。有关更多信息,请参阅 LICENSE。