Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active July 19, 2025 05:48
Show Gist options
  • Save JadenGeller/84b75486431976522c81d42779d5de2a to your computer and use it in GitHub Desktop.
Save JadenGeller/84b75486431976522c81d42779d5de2a to your computer and use it in GitHub Desktop.
async onChange with cancelation
struct OnChangeTask<T: Equatable>: ViewModifier {
let value: T
let action: () async -> Void
@State private var updateCount = 0
func body(content: Content) -> some View {
content
.onChange(of: value) {
updateCount += 1
}
.task(id: updateCount) {
guard updateCount > 0 else { return }
await action()
}
}
}
@JadenGeller
Copy link
Author

unlike task, this doesn't run with the initial value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment