Skip to content

Instantly share code, notes, and snippets.

@candostdagdeviren
Last active November 28, 2018 10:09
Show Gist options
  • Save candostdagdeviren/be241312a729acce44b5a2623d39bcfb to your computer and use it in GitHub Desktop.
Save candostdagdeviren/be241312a729acce44b5a2623d39bcfb to your computer and use it in GitHub Desktop.
Swift Post Concurrency Blog Post Code Example
class FetchRestaurantInventoryOperation: Operation {
var restaurantData: RestaurantData
var networkProvider: NetworkProvider
// 1
private var _executing = false {
willSet {
willChangeValue(forKey: "isExecuting")
}
didSet {
didChangeValue(forKey: "isExecuting")
}
}
// 1
private var _finished = false {
willSet {
willChangeValue(forKey: "isFinished")
}
didSet {
didChangeValue(forKey: "isFinished")
}
}
init(restaurantData: RestaurantData, networkProvider: NetworkProvider) {
self.restaurantData = restaurantData
self.networkProvider = networkProvider
}
// 2
override func main() {
if isCancelled {
self.finish(true)
return
}
self.executing(true)
self.networkProvider.fetchInventory() { jsonData in
if let json = jsonData, !json.isEmpty {
guard let serializedDictionary = try? JSONSerialization.jsonObject(with: json, options: []) as? [String: Any] else { return }
self.restaurantData.setInventoryJSON(serializedDictionary)
self.restaurantData.state = .downloaded
} else {
self.restaurantData.state = .failed
}
self.executing(false)
self.finish(true)
}
}
// 2
override var isExecuting: Bool {
return _executing
}
// 2
override var isAsynchronous: Bool {
return true
}
// 2
override var isFinished: Bool {
return _finished
}
// Helper methods
func executing(_ executing: Bool) {
_executing = executing
}
func finish(_ finished: Bool) {
_finished = finished
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment