Last active
January 13, 2021 00:20
-
-
Save swhitty/0d40457a7dc8a6748066029e999a5dbf to your computer and use it in GitHub Desktop.
Helper to make concurrent task group with any number of operations
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
import _Concurrency | |
extension Task { | |
// Create group with n tasks, executed concurrently. | |
// Returned array preserves original order of operations. | |
static func withGroup<TaskResult>(operations: [() async throws -> TaskResult]) async throws -> [TaskResult] { | |
return try await Task.withGroup(resultType: (Int, TaskResult).self) { group in | |
for (idx, provider) in operations.enumerated() { | |
await group.add { | |
(idx, try await provider()) | |
} | |
} | |
var results: [TaskResult?] = operations.map { _ in nil } | |
while let (idx, result) = try await group.next() { | |
results[idx] = result | |
} | |
return results.compactMap { $0 } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment