Skip to content

Instantly share code, notes, and snippets.

@x0000ff
Created June 11, 2017 02:12
Show Gist options
  • Select an option

  • Save x0000ff/1346cb22add0d15550fcfb549fed0779 to your computer and use it in GitHub Desktop.

Select an option

Save x0000ff/1346cb22add0d15550fcfb549fed0779 to your computer and use it in GitHub Desktop.
AsyncOperation in Swift
import Foundation
open class AsyncOperation: Operation {
public enum State: String {
case Ready, Executing, Finished
fileprivate var keyPath: String {
return "is" + rawValue
}
}
public var state = State.Ready {
willSet {
willChangeValue(forKey: newValue.keyPath)
willChangeValue(forKey: state.keyPath)
}
didSet {
didChangeValue(forKey: oldValue.keyPath)
didChangeValue(forKey: state.keyPath)
}
}
}
extension AsyncOperation {
override open var isReady: Bool {
return super.isReady && state == .Ready
}
override open var isExecuting: Bool {
return state == .Executing
}
override open var isFinished: Bool {
return state == .Finished
}
override open var isAsynchronous: Bool {
return true
}
override open func start() {
if isCancelled {
state = .Finished
return
}
main()
state = .Executing
}
open override func cancel() {
state = .Finished
}
}
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let queue = OperationQueue()
let imageLoad = ImageLoadOperation()
imageLoad.inputName = "train_dusk.jpg"
queue.addOperation(imageLoad)
duration {
queue.waitUntilAllOperationsAreFinished()
}
imageLoad.outputImage
PlaygroundPage.current.finishExecution()
import UIKit
public func simulateNetworkLoadImage(named: String?) -> UIImage? {
sleep(1)
guard let named = named else { return .none }
return UIImage(named: named)
}
public func simulateAsyncNetworkLoadImage(named: String?, callback: @escaping (UIImage?) -> ()) {
OperationQueue().addOperation {
let image = simulateNetworkLoadImage(named: named)
callback(image)
}
}
class ImageLoadOperation: AsyncOperation {
var inputName: String?
var outputImage: UIImage?
override func main() {
simulateAsyncNetworkLoadImage(named: inputName) { (result: UIImage?) in
self.outputImage = result
self.state = .Finished
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment