Skip to content

Instantly share code, notes, and snippets.

View SebastianBoldt's full-sized avatar
:octocat:

Sebastian Boldt SebastianBoldt

:octocat:
View GitHub Profile
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 {
do {
let text = try await createText()
await MainActor.run {
// Update your UI
}
} catch {
print(error.localizedDescription)
}
func createText() async throws -> String {
let text = try await requestTextFromServer() // function will be suspended
return text
}
func createText() async throws -> String {
// ....
}