Skip to content

Instantly share code, notes, and snippets.

View SebastianBoldt's full-sized avatar
:octocat:

Sebastian Boldt SebastianBoldt

:octocat:
View GitHub Profile
func getDocuments(range: Range<Int>) async throws -> [Data] {
// 1.
let documents = try await withThrowingTaskGroup(of: Data.self, returning: [Data].self,body: { group -> [Data] in
// 2.
for i in range {
group.addTask(priority: .high, operation: { () -> Data in
return try await getDocument(fileName: "Document-\(i)")
})
}
let task = Task {
for i in 0..<1_000_000_000_000_000 {
try Task.checkCancellation()
print(i)
}
}
task.cancel()
let task = Task {
for i in 0..<1_000_000_000_000_000 {
guard !Task.isCancelled else {
break
}
print(i)
}
}
task.cancel()
func getUser() async throws -> User {
try await Task.sleep(nanoseconds: 1_000_000)
let task = Task(priority: .high) { () -> Address in
try await Task.sleep(nanoseconds: 1_000_000)
return Address(street: "FooStreet")
}
let address = try await task.value
return User(name: "Max", address: address)
}
let task = Task(priority: .medium) { () -> String in
let text = try await requestTextFromServer()
return text
}
let task = Task { () -> String in
let text = try await requestTextFromServer()
return text
}
let result = try await task.result
switch result {
case let .success(value):
print(value)
case let .failure(error):
let task = Task { () -> String in
let text = try await requestTextFromServer()
return text
}
let newValue = try await task.value // Will only return if the Task did not throw
// Will immediatly start running after creation
let task = Task { () -> String in
let text = try await requestTextFromServer()
return text
}
struct ContentView: View {
private let formatter = {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .medium
return formatter
}()
private let timerSequence = Timer.publish(every: 1,
tolerance: 1,
let url = URL(string:"https://www.sebastianboldt.com")
let pollingSequence = URLPollingSequence(url: url!, delay: 2)
do {
for try await item in pollingSequence {
guard let data = item else {
continue
}
print(String(data: data, encoding: String.Encoding.utf8) ?? "Not decodable")
}
} catch {