Skip to content

Instantly share code, notes, and snippets.

@pipacs
Created December 12, 2018 21:27
Show Gist options
  • Save pipacs/d4b689e2a4f7b30c1492a97355887513 to your computer and use it in GitHub Desktop.
Save pipacs/d4b689e2a4f7b30c1492a97355887513 to your computer and use it in GitHub Desktop.
An (NS)Operation wrapping a Promise
import Foundation
import PromiseKit
class PromiseOperation<T>: Operation {
var result: T? = nil
var error: Error?
var promise: Promise<T>
override var isExecuting: Bool {
get {return _isExecuting}
set {
willChangeValue(forKey: "isExecuting")
_isExecuting = newValue
didChangeValue(forKey: "isExecuting")
}
}
private var _isExecuting = false
override var isFinished: Bool {
get {return _isFinished}
set {
willChangeValue(forKey: "isFinished")
_isFinished = newValue
didChangeValue(forKey: "isFinished")
}
}
private var _isFinished = false
init(promise: Promise<T>) {
self.promise = promise
}
override func start() {
Log()
self.isExecuting = true
self.isFinished = false
promise.done { result -> Void in
self.result = result
self.error = nil
}.ensure {
self.isExecuting = false
self.isFinished = true
}.catch { error in
self.result = nil
self.error = error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment