Skip to content

Instantly share code, notes, and snippets.

@Josscii
Created May 5, 2020 07:33
Show Gist options
  • Save Josscii/48a97bf45c525fa66dc253fdcb3866de to your computer and use it in GitHub Desktop.
Save Josscii/48a97bf45c525fa66dc253fdcb3866de to your computer and use it in GitHub Desktop.
一个简单常用的异步 Operation 实现
// https://www.avanderlee.com/swift/asynchronous-operations/
class AsyncOperation: Operation {
private let lockQueue = DispatchQueue(label: "com.swiftlee.asyncoperation", attributes: .concurrent)
override var isAsynchronous: Bool {
return true
}
private var _isExecuting: Bool = false
override private(set) var isExecuting: Bool {
get {
return lockQueue.sync { () -> Bool in
return _isExecuting
}
}
set {
willChangeValue(forKey: "isExecuting")
lockQueue.sync(flags: [.barrier]) {
_isExecuting = newValue
}
didChangeValue(forKey: "isExecuting")
}
}
private var _isFinished: Bool = false
override private(set) var isFinished: Bool {
get {
return lockQueue.sync { () -> Bool in
return _isFinished
}
}
set {
willChangeValue(forKey: "isFinished")
lockQueue.sync(flags: [.barrier]) {
_isFinished = newValue
}
didChangeValue(forKey: "isFinished")
}
}
override func start() {
print("Starting")
guard !isCancelled else {
finish()
return
}
isFinished = false
isExecuting = true
main()
}
override func main() {
fatalError("Subclasses must implement `execute` without overriding super.")
}
func finish() {
isExecuting = false
isFinished = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment