Last active
July 5, 2018 10:29
-
-
Save Alex-Ozun/6b8c28a1938b34bca58578e18445182b to your computer and use it in GitHub Desktop.
Simple starter snippet for custom async operation
This file contains 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
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