Estoy tratando de realizar una serie de solicitudes de red y me gustaría limitar la cantidad de tareas simultáneas en el nuevo sistema Swift Concurrency. Con las colas de operaciones, maxConcurrentOperationCount . En Combine, flatMap(maxPublishers:_:) . ¿Cuál es el equivalente en el nuevo sistema Swift Concurrency?
Por ejemplo, no es muy relevante, pero considere:
func download() async throws { try await withThrowingTaskGroup(of: Void.self) { group in for i in 0..<20 { let source = sourceUrl(for: i) let destination = destinationUrl(for: i) group.addTask { let (url, _) = try await self.session.download(from: source) try? FileManager.default.removeItem(at: destination) try FileManager.default.moveItem(at: url, to: destination) } } try await group.waitForAll() } }Eso da como resultado que todas las solicitudes se ejecuten simultáneamente:
El hecho de que URLSession no httpMaximumConnectionsPerHost es interesante, pero no es el problema principal aquí. Estoy buscando, de manera más general, cómo restringir el grado de concurrencia en una serie de tareas asincrónicas que se ejecutan en paralelo.
Uno puede insertar una llamada group.next() dentro del bucle después de alcanzar un determinado conteo, por ejemplo:
func download() async throws { try await withThrowingTaskGroup(of: Void.self) { group in for i in 0..<20 { let source = sourceUrl(for: i) let destination = destinationUrl(for: i) if i >= 6 { // max of six at a time try await group.next() } group.addTask { let (url, _) = try await self.session.download(from: source) try? FileManager.default.removeItem(at: destination) try FileManager.default.moveItem(at: url, to: destination) } } try await group.waitForAll() } }Eso da como resultado no más de seis a la vez: