Last active
June 5, 2024 15:43
-
-
Save robertmryan/0a5f508523116ee7f020559bc95e5530 to your computer and use it in GitHub Desktop.
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
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 … | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Both
data(from:)
andTask.sleep(…)
will detect cancelation and will throwCancellationError
if so, so no additional test ofTask.isCancelled
is needed. Probably better to just rethrow theCancellationError
.