Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active June 5, 2024 15:43
Show Gist options
  • Save robertmryan/0a5f508523116ee7f020559bc95e5530 to your computer and use it in GitHub Desktop.
Save robertmryan/0a5f508523116ee7f020559bc95e5530 to your computer and use it in GitHub Desktop.
var task: Task<Void, Error>?
let (stream, continuation) = AsyncStream.makeStream(of: URL.self)
task = Task {
for await url in stream {
do {
print("Sending request to \(url)")
let (data, response) = try await URLSession.shared.data(from: url)
// do something with data & response
// wait 2 seconds before getting the next URL
try await Task.sleep(for: .seconds(2))
} catch let error as CancellationError {
throw error
} catch {
// handle network errors, but proceed iterating through the stream …
}
}
}
@robertmryan
Copy link
Author

Both data(from:) and Task.sleep(…) will detect cancelation and will throw CancellationError if so, so no additional test of Task.isCancelled is needed. Probably better to just rethrow the CancellationError.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment