TypedOperation提供了对NSOperations的类型安全、可链式、可嵌套的组成。
func doComputation() -> Int
let result: TypedOperation<Int> = TypedOperation {
doComputation()
}
result.map { someValue in
someValue * 10
}
try result.awaitResult() // 100
TypedOperation<Int>(constant: 10).flatMap { someInt in
TypedOperation(constant: someInt * 2)
}.awaitResult() // -> 20 :: Int
enum Error: ErrorType {
case SomeError
}
let handled = TypedOperation<Int>(error: Error.SomeError).handle { error in
return 10
}
handled.awaitResult() // => 10
使用另一个TypedOperation
来恢复
let rescued = TypedOperation<Int>(error: Error.SomeError).rescue { error in
return TypedOperation<Int>(constant: 10)
}
rescued.awaitResult() // => 10
TypedOperation(constant: 10).onSuccess { result in
print("Result was \(result)")
}.onFailure { error in
print("Error was \(error)")
}
let joinedOperation = TypedOperation(constant: 10).join(TypedOperation(constant: 20))
try joinedOperation.awaitResult() // => Tuple2(10, 20)
许多现有的库提供接受回调函数的异步方法。使用AsynchOperationAdapter
,您可以将这些现有的异步操作包装成TypedOperations
。
protocol SomeService {
func doAsyncThing(callback: (ResultType?, NSError?) -> ())
}
let service: SomeService = /* ... */
AsyncOperationAdapter<ResultType> { service.doAsyncThing(callback: $0) }
或者使用NSURLSessions
let url: NSURL! = NSURL(string: "http://api.example.com")
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let op = AsyncOperationAdapter<NSData> { completionHandler in
let task = session.dataTaskWithURL(url) { (maybeData, maybeResponse, maybeError) in
completionHandler(maybeData, maybeError)
}
task.resume()
}
op.onSuccess { (response: NSData) in
print(response)
}
TypedOperation作为一个cocoapod提供。在您的Podfile
中添加
pod 'TypedOperation'
然后执行常规操作并运行
$ pod install
如果一切顺利,打开生成的(或更新的)xcworkspace,并在您想使用TypedOperation
的任何文件中添加以下内容
import TypedOperation