Created
April 10, 2025 08:34
-
-
Save jacobsapps/b069b5d0d549638ac6fe33a1a340596c to your computer and use it in GitHub Desktop.
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
class PollingManager { | |
private var tasks: [UUID: Task<Double, Never>] = [:] | |
func uploadDataAndReturnCash(for categories: [Category]) async -> Double? { | |
try? await uploadDataToBackend(categories) | |
for category in categories { | |
let taskID = UUID() | |
let task = Task.detached { [weak self] in | |
return (try? await self?.pollBackend(for: category)) ?? 0.0 | |
} | |
tasks[taskID] = task | |
} | |
return await collectResults() | |
} | |
private func collectResults() async -> Double { | |
var total: Double = 0 | |
for (id, task) in tasks { | |
let result = await task.value | |
total += result | |
} | |
return total | |
} | |
// illustrative | |
private func uploadDataToBackend(_ categories: [Category]) async throws { } | |
func cancelAll() { | |
for (_, task) in tasks { | |
task.cancel() | |
} | |
tasks.removeAll() | |
} | |
private func pollBackend(for category: Category) async throws -> Double { | |
try await Task.sleep(for: .seconds(10)) | |
if let cash = cash(for: category) { | |
return cash | |
} else { | |
return try await pollBackend(for: category) | |
} | |
} | |
// illustrative | |
private func cash(for category: Category) -> Double? { | |
return 4 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment