Created
August 12, 2024 05:04
-
-
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
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
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