Skip to content

Instantly share code, notes, and snippets.

@Alex-Ozun
Last active July 5, 2018 10:29
Show Gist options
  • Save Alex-Ozun/6b8c28a1938b34bca58578e18445182b to your computer and use it in GitHub Desktop.
Save Alex-Ozun/6b8c28a1938b34bca58578e18445182b to your computer and use it in GitHub Desktop.
Simple starter snippet for custom async operation
public class AsyncOperation: Operation {
public enum OperationError: Error {
case cancelled
}
public var isFailed: Bool = false
private var _completion: (Error?) -> Void
private var _execution: ((Error?) -> Void) -> Void
private var _isFinished = false
private var _isExecuting = false
public init(execution: @escaping ((Error?) -> Void) -> Void,
completion: @escaping (Error?) -> Void) {
_execution = execution
_completion = completion
super.init()
}
public override var isFinished: Bool {
return _isFinished
}
public override var isExecuting: Bool {
return _isExecuting
}
public override func start() {
willChangeValue(forKey: "isExecuting")
_isExecuting = true
didChangeValue(forKey: "isExecuting")
_execution() { error in
guard !self.isCancelled else {
_completion(OperationError.cancelled)
return
}
guard error == nil else {
self.willChangeValue(forKey: "isFailed")
self.isFailed = true
self.didChangeValue(forKey: "isFailed")
_completion(error)
return
}
self.willChangeValue(forKey: "isExecuting")
self.willChangeValue(forKey: "isFinished")
self._isExecuting = false
self._isFinished = true
self.didChangeValue(forKey: "isExecuting")
self.didChangeValue(forKey: "isFinished")
_completion(nil)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment