项目作者: ChimeHQ

项目描述 :
NSOperation's missing pieces
高级语言: Swift
项目地址: git://github.com/ChimeHQ/OperationPlus.git
创建时间: 2019-02-01T00:31:00Z
项目社区:https://github.com/ChimeHQ/OperationPlus

开源协议:BSD 3-Clause "New" or "Revised" License

下载




Build Status
Platforms

OperationPlus

OperationPlus is a set of NSOperation subclasses and extensions on NSOperation/NSOperationQueue. Its goal is to fill in the API’s missing pieces. You don’t need to learn anything new to use it.

NSOperation has been around for a long time, and there are now two potential first-party alternatives, Combine and Swift concurrency. OperationPlus includes some facilities to help Combine and NSOperation interoperate conveniently.

Integration

Swift Package Manager:

  1. dependencies: [
  2. .package(url: "https://github.com/ChimeHQ/OperationPlus.git")
  3. ]

NSOperation Subclasses

  • BaseOperation: provides core functionality for easier NSOperation subclassing
  • AsyncOperation: convenience wrapper around BaseOperation for async support
  • AsyncBlockOperation: convenience class for inline async support
  • (Async)ProducerOperation: produces an output
  • (Async)ConsumerOperation: accepts an input from a ProducerOperation
  • (Async)ConsumerProducerOperation: accepts an input from a ProducerOperation and also produces an output

BaseOperation

This is a simple NSOperation subclass built for easier extensibility. It features:

  • Thread-safety
  • Timeout support
  • Easier cancellation handling
  • Stricter state checking
  • Built-in asynchrous support
  • Straight-foward customization
  1. let a = BaseOperation(timeout: 5.0)
  2. // NSOperation will happily allow you do this even
  3. // if `a` has finished. `BaseOperation` will not.
  4. a.addDependency(another)
  5. // ...
  6. public override func main() {
  7. // This will return true if your operation is cancelled, timed out,
  8. // or prematurely finished. ProducerOperation subclass state will be
  9. // handled correctly as well.
  10. if self.checkForCancellation() {
  11. return
  12. }
  13. }
  14. // ...

AsyncOperation

A BaseOperation subclass that can be used for your asynchronous operations. These are any operations that need to extend their lifetime past the main method.

  1. import Foundation
  2. import OperationPlus
  3. class MyAsyncOperation: AsyncOperation {
  4. public override func main() {
  5. DispatchQueue.global().async {
  6. if self.checkForCancellation() {
  7. return
  8. }
  9. // do stuff
  10. self.finish()
  11. }
  12. }
  13. }

There’s also nothing special about this class at all — it’s there just for convenience. If you want, you can just subclass BaseOperation directly and override one method.

  1. import Foundation
  2. import OperationPlus
  3. class MyAsyncOperation: BaseOperation {
  4. override open var isAsynchronous: Bool {
  5. return true
  6. }
  7. }

ProducerOperation

A BaseOperation subclass that yields a value. Includes a completion handler to access the value.

  1. import Foundation
  2. import OperationPlus
  3. class MyValueOperation: ProducerOperation<Int> {
  4. public override func main() {
  5. // do your computation
  6. self.finish(with: 42)
  7. }
  8. }
  9. // ...
  10. let op = MyValueOperation()
  11. op.resultCompletionBlock = { (value) in
  12. // use value here
  13. }

AsyncProducerOperation

A variant of ProducerOperation that may produce a value after the main method has completed executing.

  1. import Foundation
  2. import OperationPlus
  3. class MyAsyncOperation: AsyncProducerOperation<Int> {
  4. public override func main() {
  5. DispatchQueue.global().async {
  6. if self.checkForCancellation() {
  7. return
  8. }
  9. // do stuff
  10. self.finish(with: 42)
  11. }
  12. }
  13. }

ConsumerOperation and AsyncConsumerOperation

A BaseOperation sublass that accepts the input of a ProducerOperation.

  1. import Foundation
  2. import OperationPlus
  3. class MyConsumerOperation: ConsumerOperation<Int> {
  4. override func main() {
  5. guard let value = producerValue else {
  6. // handle failure in some way
  7. }
  8. }
  9. override func main(with value: Int) {
  10. // make use of value here, or automatically
  11. // fail if it wasn't successfully produced
  12. }
  13. }
  14. let op = MyConsumerOperation(producerOp: myIntProducerOperation)

AsyncBlockOperation

A play on NSBlockOperation, but makes it possible to support asynchronous completion without making an Operation subclass. Great for quick, inline work.

  1. let op = AsyncBlockOperation { (completionBlock) in
  2. DispatchQueue.global().async {
  3. // do some async work here, just be certain to call
  4. // the completionBlock when done
  5. completionBlock()
  6. }
  7. }

NSOperation/NSOperationQueue Extensions

Queue creation conveniences:

  1. let a = OperationQueue(name: "myqueue")
  2. let b = OperationQueue(name: "myqueue", maxConcurrentOperations: 1)
  3. let c = OperationQueue.serialQueue()
  4. let d = OperationQueue.serialQueue(named: "myqueue")

Enforcing runtime constraints on queue execution:

  1. OperationQueue.preconditionMain()
  2. OperationQueue.preconditionNotMain()

Consise dependencies:

  1. queue.addOperation(op, dependency: opA)
  2. queue.addOperation(op, dependencies: [opA, opB])
  3. queue.addOperation(op, dependencies: Set([opA, opB]))
  4. op.addDependencies([opA, opB])
  5. op.addDependencies(Set([opA, opB]))

Queueing work when a queue’s current operations are complete:

  1. queue.currentOperationsFinished {
  2. print("all pending ops done")
  3. }

Convenient inline functions:

  1. queue.addAsyncOperation { (completionHandler) in
  2. DispatchQueue.global().async {
  3. // do some async work
  4. completionHandler()
  5. }
  6. }

Async integration:

  1. queue.addOperation {
  2. await asyncFunction1()
  3. await asyncFunction2()
  4. }
  5. let value = try await queue.addResultOperation {
  6. try await asyncValue()
  7. }

Delays:

  1. queue.addOperation(op, afterDelay: 5.0)
  2. queue.addOperation(afterDelay: 5.0) {
  3. // work
  4. }

Combine Integration

PublisherOperation

This ProducerOperation subclass takes a publisher. When executed, it creates a subscription and outputs the results.

  1. op.publisher() // AnyPublisher<Void, Never>
  2. producerOp.outputPublisher() // AnyPublisher<Output, Never>
  1. publisher.operation() // PublisherOperation
  2. publisher.execute(on: queue) // subscribes and executes chain on queue and returns a publisher for result

XCTest Support

OperationTestingPlus is an optional micro-framework to help make your XCTest-based tests a little nicer. When using Carthage, it is built as a static framework to help ease integration with your testing targets.

FulfillExpectationOperation

A simple NSOperation that will fulfill an XCTestExpectation when complete. Super-useful when used with dependencies on your other operations.

NeverFinishingOperation

A great way to test out your Operations’ timeout behaviors.

OperationExpectation

An XCTestExpectation sublass to make testing async operations a little more XCTest-like.

  1. let op = NeverFinishingOperation()
  2. let expectation = OperationExpectation(operation: op)
  3. expectation.isInverted = true
  4. wait(for: [expectation], timeout: 1.0)

Suggestions or Feedback

We’d love to hear from you! Get in touch via an issue or pull request.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.