Skip to content

Instantly share code, notes, and snippets.

@piyushdec
Last active July 28, 2019 19:50
Show Gist options
  • Save piyushdec/2607b90a9460ebaffa3913d7119d5b52 to your computer and use it in GitHub Desktop.
Save piyushdec/2607b90a9460ebaffa3913d7119d5b52 to your computer and use it in GitHub Desktop.
class CustomOperation: Operation {
// MARK: - Types
//Step 1: define oppration states
enum State {
case isReady, isExecuting, isFinished
var keyPath: String {
switch self {
case .isReady: return "isReady"
case .isExecuting: return "isExecuting"
case .isFinished: return "isFinished"
}
}
}
//Step 2: setup state observers
var state: State = .isReady {
willSet {
willChangeValue(forKey: newValue.keyPath) //new value
willChangeValue(forKey: state.keyPath) //current value
}
didSet {
didChangeValue(forKey: oldValue.keyPath) //old value
didChangeValue(forKey: state.keyPath) //current value
}
}
//Step 3: override state properties
override var isReady: Bool {
return super.isReady && state == .isReady
}
override var isExecuting: Bool {
return state == .isExecuting
}
override var isFinished: Bool {
return state == .isFinished
}
override var isAsynchronous: Bool {
return true
}
}
class ImageDownloadHelper: CustomOperation {
let imageRecord: ImageRecord
init(_ imageRecord: ImageRecord) {
self.imageRecord = imageRecord
}
override func start() {
if isCancelled {
state = .isFinished
} else {
state = .isReady
main()
}
}
override func main() {
if isCancelled {
state = .isFinished
return
}
state = .isExecuting
guard let imageData = try? Data(contentsOf: imageRecord.url) else { return }
if !imageData.isEmpty {
imageRecord.image = UIImage(data:imageData)
imageRecord.state = .downloaded
} else {
imageRecord.state = .failed
imageRecord.image = UIImage(named: "Failed")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment