Skip to content

Instantly share code, notes, and snippets.

@john-crossley
Created May 20, 2018 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-crossley/5d9f1bc956f0fb32852ec6ce9346dc7f to your computer and use it in GitHub Desktop.
Save john-crossley/5d9f1bc956f0fb32852ec6ce9346dc7f to your computer and use it in GitHub Desktop.
AsyncOperation wrapper for OperationQueue
class AsyncOperation: Operation {
enum State: String {
case ready = "Ready"
case executing = "Executing"
case finished = "Finished"
fileprivate var keyPath: String {
return "is" + rawValue
}
}
var state: State = .ready {
willSet {
willChangeValue(forKey: newValue.keyPath)
willChangeValue(forKey: state.keyPath)
}
didSet {
didChangeValue(forKey: oldValue.keyPath)
didChangeValue(forKey: state.keyPath)
}
}
}
extension AsyncOperation {
override var isReady: Bool {
return super.isReady && state == .ready
}
override var isExecuting: Bool {
return state == .executing
}
override var isFinished: Bool {
return state == .finished
}
override var isAsynchronous: Bool {
return true
}
override func start() {
if isCancelled {
state = .finished
return
}
main()
state = .executing
}
override func cancel() {
state = .finished
}
}
@john-crossley
Copy link
Author

Extend it, overwrite main() and don't forget to call self.state = .finished when you've completed your operation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment