Skip to content

Instantly share code, notes, and snippets.

@aaronlab
Last active December 17, 2021 07:55
Show Gist options
  • Save aaronlab/d8088cb8981faac7a1c4c3d8934495bd to your computer and use it in GitHub Desktop.
Save aaronlab/d8088cb8981faac7a1c4c3d8934495bd to your computer and use it in GitHub Desktop.
AsyncOperation
import Foundation
class AsyncOperation: Operation {
enum State: String {
case ready, executing, finished
fileprivate var keyPath: String {
return "is\(rawValue.capitalized)"
}
}
var state = State.ready {
willSet {
willChangeValue(forKey: newValue.keyPath)
willChangeValue(forKey: state.keyPath)
}
didSet {
didChangeValue(forKey: oldValue.keyPath)
didChangeValue(forKey: state.keyPath)
}
}
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment