Created
June 30, 2025 13:33
-
-
Save rnapier/f8f27580085fe5ba9d26da5f2d521a9b to your computer and use it in GitHub Desktop.
TaskBag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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