Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
How to write and use an asynchronous operation
import Foundation
class AsyncOperation: Operation {
enum State: String {
case isReady, isExecuting, isFinished
}
override var isAsynchronous: Bool {
return true
}
var state = State.isReady {
willSet {
willChangeValue(forKey: state.rawValue)
willChangeValue(forKey: newValue.rawValue)
}
didSet {
didChangeValue(forKey: oldValue.rawValue)
didChangeValue(forKey: state.rawValue)
}
}
override var isExecuting: Bool {
return state == .isExecuting
}
override var isFinished: Bool {
return state == .isFinished
}
override func start() {
guard !self.isCancelled else {
state = .isFinished
return
}
state = .isExecuting
main()
}
}
final class FetchOperation: AsyncOperation {
private(set) var dataFetched: Data?
private let session = URLSession(configuration: .default)
private var dataTask: URLSessionDataTask?
override func main() {
let url = URL(string: "https://jsonplaceholder.typicode.com/users")!
dataTask = session.dataTask(with: url) {[unowned self] (data, _, _) in
guard !self.isCancelled else {
self.state = .isFinished
return
}
guard let data = data else { return }
self.dataFetched = data
self.state = .isFinished
}
dataTask?.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment