Skip to content

Instantly share code, notes, and snippets.

@sidepelican
Created January 13, 2022 09:12
Show Gist options
  • Save sidepelican/b8962cbe40dacc5a1431f4466de723cc to your computer and use it in GitHub Desktop.
Save sidepelican/b8962cbe40dacc5a1431f4466de723cc to your computer and use it in GitHub Desktop.
.task{}のバックポート検討
import SwiftUI
func longlongAsyncFunction() async {
let id = UUID()
print("\(id): start")
do {
try await withTaskCancellationHandler {
try await Task.sleep(nanoseconds: 1000 * 1000 * 1000 * 10)
print("\(id): end")
} onCancel: {
print("\(id): cancel")
}
} catch {
print("\(error)")
}
}
struct CountView: View {
@State var count = 0
var body: some View {
VStack {
Text("Hello \(count)")
Button("Tap") {
count += 1
}
}
.task2 {
await longlongAsyncFunction()
}
// .modifier(TaskModifier {
// await longlongAsyncFunction()
// })
}
}
struct ContentView: View {
@State var count = 0
var body: some View {
NavigationView {
NavigationLink("Next") {
CountView()
}
}
}
}
public extension View {
func task2(
priority: TaskPriority = .userInitiated,
_ action: @escaping @Sendable () async -> ()
) -> some View {
var task: Task<(), Never>?
return onAppear {
task = Task(priority: priority, operation: action)
}
.onDisappear {
task?.cancel()
}
}
}
struct TaskModifier: ViewModifier {
var action: @Sendable () async -> ()
@State var task: Task<(), Never>?
func body(content: Content) -> some View {
return content.onAppear {
task = Task(operation: action)
}
.onDisappear {
task?.cancel()
}
}
}
extension UUID: @unchecked Sendable {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment