Skip to content

Instantly share code, notes, and snippets.

@cristianpalomino
Created August 13, 2019 23:15
Show Gist options
  • Save cristianpalomino/cec28364a2ea0590439384b316a1e54a to your computer and use it in GitHub Desktop.
Save cristianpalomino/cec28364a2ea0590439384b316a1e54a to your computer and use it in GitHub Desktop.
//
// AsyncOperation.swift
// SBFoundation
//
// Created by Gonzalo Reyes Huertas on 5/20/19.
// Copyright © 2019 Scotiabank. All rights reserved.
//
import Foundation
open class AsyncOperation: Operation {
// MARK: - Properties
public var state: State = .ready {
willSet {
willChangeValue(forKey: state.keyPath)
willChangeValue(forKey: newValue.keyPath)
}
didSet {
didChangeValue(forKey: oldValue.keyPath)
didChangeValue(forKey: state.keyPath)
}
}
// lifecycle flags
open override var isReady: Bool { return super.isReady && state == .ready }
open override var isExecuting: Bool { return state == .executing }
open override var isFinished: Bool { return state == .finished }
// async flag
open override var isAsynchronous: Bool { return true }
// MARK: - Lifecycle
open override func start() {
guard !isCancelled && !isFinished else {
state = .finished
return
}
state = .executing
main()
}
open override func cancel() {
state = .finished
}
}
public extension AsyncOperation {
enum State: String {
case ready
case executing
case finished
fileprivate var keyPath: String {
return "is\(rawValue.capitalized)"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment