Skip to content

Instantly share code, notes, and snippets.

@aChase55
Last active September 19, 2018 16:50
Show Gist options
  • Save aChase55/3bc4863ef74c65cc483358f738d953da to your computer and use it in GitHub Desktop.
Save aChase55/3bc4863ef74c65cc483358f738d953da to your computer and use it in GitHub Desktop.
An Operation subclass that does work asynchronously
import Foundation
class AsyncOperation: Operation {
private var _isFinished: Bool = false
private var _isExecuting: Bool = false
open func execute() { assertionFailure("Overide execute() in subclass") }
override var isAsynchronous: Bool { return true }
override var isConcurrent: Bool { return true }
override var isFinished: Bool { return _isFinished }
override var isExecuting: Bool { return _isExecuting }
final override func start() {
guard !isCancelled else {
willChangeValue(forKey: "isFinished")
_isFinished = true
didChangeValue(forKey: "isFinished")
return
}
willChangeValue(forKey: "isExecuting")
Thread.detachNewThreadSelector(#selector(main), toTarget: self, with: nil)
_isExecuting = true
didChangeValue(forKey: "isExecuting")
}
final override func main() { execute() }
//Call completeOperation() within your overriden execute method when work is completed
final func completeOperation() {
willChangeValue(forKey: "isFinished")
willChangeValue(forKey: "isExecuting")
_isExecuting = false
_isFinished = true
didChangeValue(forKey: "isExecuting")
didChangeValue(forKey: "isFinished")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment