Skip to content

Instantly share code, notes, and snippets.

@rnapier
Created June 30, 2025 13:33
Show Gist options
  • Save rnapier/f8f27580085fe5ba9d26da5f2d521a9b to your computer and use it in GitHub Desktop.
Save rnapier/f8f27580085fe5ba9d26da5f2d521a9b to your computer and use it in GitHub Desktop.
TaskBag
public actor TaskBag {
private var tasks: [UUID: Task<Void, Never>] = [:]
func add(_ task: Task<Void, Never>) {
let id = UUID()
tasks[id] = Task { [weak self] in
await task.value
await self?.remove(id: id)
}
}
private func remove(id: UUID) {
tasks.removeValue(forKey: id)
}
private static func shutdown(tasks: some Collection<Task<Void, Never>>) async {
for task in tasks {
task.cancel()
}
for task in tasks {
await task.value
}
}
public func shutdown() async {
await Self.shutdown(tasks: tasks.values)
}
deinit {
Task { [tasks] in
await Self.shutdown(tasks: tasks.values)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment