Skip to content

Instantly share code, notes, and snippets.

@sanghapark
Created February 20, 2017 09:31
Show Gist options
  • Save sanghapark/8a463ea54985cae2568ef4b42ffca4c4 to your computer and use it in GitHub Desktop.
Save sanghapark/8a463ea54985cae2568ef4b42ffca4c4 to your computer and use it in GitHub Desktop.
AsyncOperation subclassing Operation for asynchronous operation
class AsyncOperation: Operation {
enum State: String {
case Ready, Executing, 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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment