Created
August 17, 2018 15:00
-
-
Save FWEugene/af40e1ff45036ed5a31aa328c969dcfb to your computer and use it in GitHub Desktop.
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
// | |
// ConcurrentOperation.swift | |
// Yevgeniy Prokoshev | |
// | |
// Created by Yevgeniy Prokoshev on 14/08/2018. | |
// Copyright © 2018 Yevgeniy Prokoshev. All rights reserved. | |
// | |
import Foundation | |
open class ConcurrentOperation: Operation { | |
enum State: String { | |
case Ready = "isReady" | |
case Executing = "isExecuting" | |
case Finished = "isFinished" | |
fileprivate func associatedKey() -> String { | |
switch self { | |
case .Ready: | |
return #keyPath(Operation.isReady) | |
case .Executing: | |
return #keyPath(Operation.isExecuting) | |
case .Finished: | |
return #keyPath(Operation.isFinished) | |
} | |
} | |
} | |
var state: State = .Ready { | |
willSet { | |
willChangeValue(forKey: newValue.rawValue) | |
willChangeValue(forKey: state.rawValue) | |
} | |
didSet { | |
didChangeValue(forKey: oldValue.rawValue) | |
didChangeValue(forKey: state.rawValue) | |
} | |
} | |
open override var isReady: Bool { | |
get { | |
return state == .Ready | |
} | |
} | |
override open var isAsynchronous: Bool { return true } | |
override open var isExecuting: Bool { | |
get { | |
return state == .Executing | |
} | |
} | |
override open var isFinished: Bool { | |
get { | |
return state == .Finished | |
} | |
} | |
override open func start() { | |
guard !self.isCancelled else { | |
self.completeOperation() | |
return | |
} | |
self.state = .Executing | |
self.executeOperation() | |
} | |
override open func main() { | |
guard !self.isCancelled else { | |
self.completeOperation() | |
return | |
} | |
self.state = .Executing | |
self.executeOperation() | |
} | |
func executeOperation() { | |
assertionFailure("Override in subclass") | |
} | |
func completeOperation() { | |
self.state = .Finished | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment