Last active
July 13, 2024 19:32
-
-
Save mrdekk/5f9af5cb2d1c8df3a72349a556ece18b to your computer and use it in GitHub Desktop.
Simple Swift AsyncOperation
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
class AsyncOperation : Operation { | |
private var _isExecuting = false | |
private var _isFinished = false | |
override func start() { | |
guard !isCancelled else { | |
finish() | |
return | |
} | |
willChangeValue(forKey: "isExecuting") | |
_isExecuting = true | |
main() | |
didChangeValue(forKey: "isExecuting") | |
} | |
override func main() { | |
// NOTE: should be overriden | |
finish() | |
} | |
func finish() { | |
willChangeValue(forKey: "isFinished") | |
_isFinished = true | |
didChangeValue(forKey: "isFinished") | |
} | |
override var isAsynchronous: Bool { | |
return true | |
} | |
override var isExecuting: Bool { | |
return _isExecuting | |
} | |
override var isFinished: Bool { | |
return _isFinished | |
} | |
} | |
class MyAsyncOperation: AsyncOperation { | |
override func main() { | |
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in | |
guard let self = self else { return } | |
// do the work | |
print("Hello3") | |
self.finish() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment