Create a gist now

Instantly share code, notes, and snippets.

Embed
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()
}
}
@robwithhair

This comment has been minimized.

Show comment
Hide comment
@robwithhair

robwithhair Jun 1, 2018

Is this thread safe? I'm reading lots about thread safety of writing to state. I'm bit confused.

Is this thread safe? I'm reading lots about thread safety of writing to state. I'm bit confused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment