Skip to content

Instantly share code, notes, and snippets.

@HarshilShah
Created August 12, 2024 05:04
Show Gist options
  • Save HarshilShah/f27d44420e1629ef79de3ec986d25b34 to your computer and use it in GitHub Desktop.
Save HarshilShah/f27d44420e1629ef79de3ec986d25b34 to your computer and use it in GitHub Desktop.
A SwiftUI Task modifier that gives you the current and previous ID values in the body
public extension View {
func task<T: Equatable>(
id: T,
priority: TaskPriority = .userInitiated,
@_inheritActorContext _ action: @Sendable @escaping (T, T) async -> Void
) -> some View {
self.modifier(TaskViewModifier(id: id, priority: priority, action: action))
}
}
struct TaskViewModifier<T: Equatable>: ViewModifier {
var id: T
var priority: TaskPriority
var action: @Sendable (T, T) async -> Void
@State private var previousID: T?
func body(content: Content) -> some View {
content
.task(id: id, priority: priority) {
defer { previousID = id }
await action(previousID ?? id, id)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment