Created
June 7, 2018 22:38
-
-
Save deda9/a57ab64ded016ad2924c846cfebcdcf6 to your computer and use it in GitHub Desktop.
How to create Concurrency custom operation block
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
enum OperationState: Int { | |
case ready | |
case executing | |
case finished | |
} | |
class CustomOperationBlock: Operation{ | |
private var state: OperationState! | |
private let finishedKey = "isFinished" | |
private let executingKey = "isExecuting" | |
override init(){ | |
self.state = .ready | |
} | |
override func start() { | |
guard !self.isCancelled else{ | |
setIsFinished() | |
return | |
} | |
self.willChangeValue(forKey: executingKey) | |
Thread.detachNewThreadSelector(#selector(main), toTarget: self, with: nil) | |
self.state = .executing | |
self.didChangeValue(forKey: executingKey) | |
} | |
override func main() { | |
doWork() | |
setIsFinished() | |
} | |
private func setIsFinished(){ | |
self.willChangeValue(forKey: finishedKey) | |
self.state = .finished | |
self.didChangeValue(forKey: finishedKey) | |
} | |
private func doWork(){ | |
print("Here doing workin for operation") | |
} | |
override var isConcurrent: Bool{ | |
return true | |
} | |
override var isFinished: Bool{ | |
return state == .finished | |
} | |
override var isExecuting: Bool{ | |
return state == .executing | |
} | |
} | |
let customOperation = CustomOperationBlock() | |
customOperation.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment