Created
January 13, 2022 09:12
-
-
Save sidepelican/b8962cbe40dacc5a1431f4466de723cc to your computer and use it in GitHub Desktop.
.task{}のバックポート検討
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
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