AsyncBlockOperation
final class AsyncBlockOperation: AsyncOperation { | |
private var block: (AsyncBlockOperation) -> Void | |
init(_ block: @escaping (AsyncBlockOperation) -> Void) { | |
self.block = block | |
} | |
override func main() { | |
let wasExecuting = (state == .executing) | |
super.main() | |
if !wasExecuting { | |
block(self) | |
} | |
} | |
} | |
open class AsyncOperation: Operation { | |
public enum State: String { | |
case ready = "Ready" | |
case executing = "Executing" | |
case finished = "Finished" | |
fileprivate var keyPath: String { return "is" + self.rawValue } | |
} | |
override open var isAsynchronous: Bool { true } | |
override open var isExecuting: Bool { state == .executing } | |
override open var isFinished: Bool { state == .finished } | |
public private(set) var state = State.ready { | |
willSet { | |
willChangeValue(forKey: state.keyPath) | |
willChangeValue(forKey: newValue.keyPath) | |
} | |
didSet { | |
didChangeValue(forKey: state.keyPath) | |
didChangeValue(forKey: oldValue.keyPath) | |
} | |
} | |
override open func start() { | |
if self.isCancelled { | |
state = .finished | |
} else { | |
state = .ready | |
main() | |
} | |
} | |
override open func main() { | |
if self.isCancelled { | |
state = .finished | |
} else { | |
state = .executing | |
} | |
} | |
public func finish() { | |
guard state != .finished else { return } | |
state = .finished | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment