I need to store the AsyncIterator
of a ThrowingTaskGroup
for later use. I’m creating this iterator inside of an async
function inside of an actor. However, as the resulting iterator
is a value type, I cannot store and later access it outside of the scope of the current function.
Is there something inherently wrong with my approach?
Here’s some code to illustrate the issue:
actor Foo {
private var iterator: ThrowingTaskGroup<String, any Error>.Iterator?
func bar() async throws {
let workItems = ["A", "B", "C", "D"]
try await withThrowingTaskGroup(of: String.self) { group in
workItems.forEach { item in
group.addTask { [unowned self] in
return try await doWork(on: item)
}
}
iterator = group.makeAsyncIterator()
guard let firstItem = try await iterator?.next() else { // Cannot call mutating async function 'next()' on actor-isolated property 'iterator'
throw "An error"
}
// do some work based on first item
}
}
private func atALaterPointInTime() async throws {
while let item = try await iterator?.next() { // Cannot call mutating async function 'next()' on
await doMoreWork(on: item)
}
}
private func doWork(on item: String) async throws -> String {
return item
}
private func doMoreWork(on item: String) async {
// ...
}
}