94 lines
2.5 KiB
Swift
94 lines
2.5 KiB
Swift
//
|
|
// Task.swift
|
|
// App
|
|
//
|
|
// Created by Marcus Handte on 22.07.22.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
public class BaseTask {
|
|
|
|
/// A dispatch queue to ensure that tasks are executed sequentially
|
|
public static let queue = DispatchQueue(label: "tasks")
|
|
|
|
/// A flag to indicate whether the operation is cancelled.
|
|
private var canceled = false
|
|
|
|
/// A lock to guard the cancelled flag.
|
|
private let lock = NSLock()
|
|
|
|
/// Creates the operation.
|
|
public init() { }
|
|
|
|
/// Determines whether the operation should be canceled.
|
|
///
|
|
/// - returns: True if the operation is canceled, false otherwise.
|
|
public func isCanceled() -> Bool {
|
|
lock.lock()
|
|
let result = canceled
|
|
lock.unlock()
|
|
return result
|
|
}
|
|
|
|
/// Cancels the upload operation.
|
|
public func cancel() {
|
|
lock.lock()
|
|
canceled = true
|
|
lock.unlock()
|
|
}
|
|
|
|
/// Executes a task an informs the completion handler on the main thread.
|
|
public func execute(completion: @escaping (Bool) -> Void) {
|
|
BaseTask.queue.async {
|
|
let result = self.executeAsync()
|
|
DispatchQueue.main.async {
|
|
completion(result)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Executes the task logic. Multiple classes
|
|
func executeAsync() -> Bool {
|
|
return true
|
|
}
|
|
|
|
/// Cancels all tasks.
|
|
public static func cancel(all tasks: [BaseTask]) {
|
|
for t in tasks {
|
|
t.cancel()
|
|
}
|
|
}
|
|
|
|
/// Executes a series of tasks until one of them fails or all complete
|
|
public static func execute(all tasks: [BaseTask], completion: @escaping (Bool) -> Void) {
|
|
if tasks.count > 0 {
|
|
var t = tasks
|
|
BaseTask.execute(current: t.removeFirst(), next: t, completion: completion)
|
|
} else {
|
|
DispatchQueue.main.async {
|
|
completion(true)
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
/// Executes the current task and continues with the next tasks, if the task is successful.
|
|
private static func execute(current: BaseTask, next: [BaseTask], completion: @escaping (Bool) -> Void) {
|
|
BaseTask.queue.async {
|
|
let result = current.executeAsync()
|
|
if !result || next.count == 0 {
|
|
DispatchQueue.main.async {
|
|
completion(result)
|
|
}
|
|
} else {
|
|
var t = next
|
|
BaseTask.execute(current: t.removeFirst(), next: t, completion: completion)
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
}
|
|
|