Skip to content

Instantly share code, notes, and snippets.

@zeitschlag
Created March 12, 2020 09:30
Show Gist options
  • Save zeitschlag/388d820946e6c8d9e499d21987366e64 to your computer and use it in GitHub Desktop.
Save zeitschlag/388d820946e6c8d9e499d21987366e64 to your computer and use it in GitHub Desktop.
This is the AsyncOperation-class from the blogpost: https://zeitschlag.net/asyncoperation/
import Foundation
class AsyncOperation: Operation {
private var asyncOperationFinished: Bool
private var asyncOperationExecuting: Bool
override init() {
self.asyncOperationFinished = false
self.asyncOperationExecuting = false
super.init()
}
override var isFinished: Bool {
return self.asyncOperationFinished
}
override var isExecuting: Bool {
return self.asyncOperationExecuting
}
override func start() {
if (self.isCancelled) {
self.willChangeValue(for: \AsyncOperation.isFinished)
self.asyncOperationFinished = true
self.didChangeValue(for: \AsyncOperation.isFinished)
return
}
self.willChangeValue(for: \AsyncOperation.isExecuting)
self.asyncOperationExecuting = true
Thread.detachNewThreadSelector(#selector(main), toTarget: self, with: nil)
self.didChangeValue(for: \AsyncOperation.isExecuting)
}
override func cancel() {
super.cancel()
self.completeOperation()
}
func operationCompletedSuccessfully() {
self.completeOperation()
}
private func completeOperation() {
self.willChangeValue(for: \AsyncOperation.isFinished)
self.willChangeValue(for: \AsyncOperation.isExecuting)
self.asyncOperationExecuting = false
self.asyncOperationFinished = true
self.didChangeValue(for: \AsyncOperation.isFinished)
self.didChangeValue(for: \AsyncOperation.isExecuting)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment