Skip to content

Instantly share code, notes, and snippets.

@mredig
Last active April 5, 2022 20:14
Show Gist options
  • Save mredig/012c445bc86de8b323dd52d37668b042 to your computer and use it in GitHub Desktop.
Save mredig/012c445bc86de8b323dd52d37668b042 to your computer and use it in GitHub Desktop.
Since `Task`s are not guaranteed to execute in the order they are created, yet it is sometimes important for them to be completed in order, this actor allows for you to add async closures to a queue in which the order is FIFO.
import Foundation
/**
Since `Task`s are not guaranteed to execute in the order they are created, yet it is sometimes important for them to be completed in order, this actor allows for you to
add async closures to a queue in which the order is FIFO.
*/
public actor AsyncTaskQueue {
public typealias TaskType = Task<Void, Error>
public private(set) var currentTask: TaskType? {
didSet {
Task {
await onQueueUpdate(self)
}
}
}
private var taskQueue: [TaskType] = []
public var numberOfTasksInQueue: Int { taskQueue.count + (currentTask == nil ? 0 : 1) }
/**
This closure is called every time the `currentTask` value changes. However, due to its nature of being called as an async `Task`, it is not guaranteed to be
called *immediately* following a value change and is instead susceptible to the nature of Swift's async `TaskPriority` based queuing.
The closure will be called on whatever actor context it is passed in as, not on `AsyncTaskQueue`'s actor.
*/
public let onQueueUpdate: @Sendable (AsyncTaskQueue) async -> Void
public init(@_inheritActorContext onQueueUpdate: @Sendable @escaping (AsyncTaskQueue) async -> Void = { _ in }) {
self.onQueueUpdate = onQueueUpdate
}
@discardableResult
public func queueNewTaskWithResult<Result>(@_inheritActorContext @_implicitSelfCapture _ block: @Sendable @escaping () async throws -> Result) async throws -> Result {
let task: Task<Result, Error> = queueNewTask(block)
return try await task.value
}
public func queueNewTask<Result>(@_inheritActorContext @_implicitSelfCapture _ block: @Sendable @escaping () async throws -> Result) -> Task<Result, Error> {
let previous = taskQueue.last ?? currentTask
let newTask = Task { () async throws -> Result in
if let previous = previous {
_ = await previous.result
}
return try await block()
}
addTaskToQueue(newTask)
return newTask
}
private func addTaskToQueue<Success>(_ task: Task<Success, Error>) {
let wrapped = Task {
_ = try await task.value
}
taskQueue.append(wrapped)
bumpQueue()
}
private func bumpQueue() {
guard currentTask == nil else { return }
guard let popped = taskQueue.popFirst() else { return }
currentTask = popped
Task {
_ = await currentTask?.result
currentTask = nil
bumpQueue()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment