Last active
December 14, 2023 19:51
-
-
Save brennanMKE/707d2ffaab047cbf7f16cfc19d83e3a6 to your computer and use it in GitHub Desktop.
DataProvider using AsyncStream
This file contains 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 Foundation | |
struct DataProvider<Element: Sendable> { | |
let stream: AsyncStream<Element> | |
private let continuation: AsyncStream<Element>.Continuation | |
init(bufferingPolicy: AsyncStream<Element>.Continuation.BufferingPolicy = .unbounded) { | |
(stream, continuation) = AsyncStream.makeStream(bufferingPolicy: bufferingPolicy) | |
} | |
func receiveNext(item: Element) { | |
continuation.yield(item) | |
} | |
func finish() { | |
continuation.finish() | |
} | |
} |
This file contains 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
func processEachItem<ItemType, ResultType>(_ items: [ItemType], operation: @escaping @Sendable (ItemType) -> ResultType) async -> [ResultType] { | |
await withTaskGroup(of: ResultType.self) { group in | |
for item in items { | |
group.addTask { | |
operation(item) | |
} | |
} | |
return await group.reduce(into: []) { $0.append($1) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment