Created
February 20, 2017 09:31
-
-
Save sanghapark/8a463ea54985cae2568ef4b42ffca4c4 to your computer and use it in GitHub Desktop.
AsyncOperation subclassing Operation for asynchronous operation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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