TypedOperation 0.0.4

TypedOperation 0.0.4

测试测试
Lang语言 SwiftSwift
许可 自定义
发布最新发布2016年6月
SPM支持SPM

Matt Gadda维护。



Typed Operation

概述

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)

包装NSURLSessionTasks

许多现有的库提供接受回调函数的异步方法。使用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