Skip to content

Instantly share code, notes, and snippets.

@deda9
Created June 7, 2018 22:38
Show Gist options
  • Save deda9/a57ab64ded016ad2924c846cfebcdcf6 to your computer and use it in GitHub Desktop.
Save deda9/a57ab64ded016ad2924c846cfebcdcf6 to your computer and use it in GitHub Desktop.
How to create Concurrency custom operation block
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