Skip to content

Instantly share code, notes, and snippets.

@LucasAbijmil
Last active September 2, 2025 08:27
Show Gist options
  • Save LucasAbijmil/2d93acfa2edbba9959aa3efb55145010 to your computer and use it in GitHub Desktop.
Save LucasAbijmil/2d93acfa2edbba9959aa3efb55145010 to your computer and use it in GitHub Desktop.
Debounce in SwiftUI using async/await, AsyncChannel & Observable macro
extension View {
// MARK: - Debounce with Binding
func debounce<T: Sendable & Equatable>(_ query: Binding<T>, using channel: AsyncChannel<T>, for duration: Duration, action: @Sendable @escaping (T) async -> Void) -> some View {
self
.task {
for await query in channel.debounce(for: duration) {
await action(query)
}
}
.task(id: query.wrappedValue) {
await channel.send(query.wrappedValue)
}
}
func debounce<T: Sendable & Equatable>(_ query: Binding<T>, using channel: AsyncChannel<T>, for duration: Duration, action: @Sendable @escaping () async -> Void) -> some View {
self
.task {
for await _ in channel.debounce(for: duration) {
await action()
}
}
.task(id: query.wrappedValue) {
await channel.send(query.wrappedValue)
}
}
// MARK: - Debounce with the wrappedValue of a Binding
func debounce<T: Sendable & Equatable>(_ query: T, using channel: AsyncChannel<T>, for duration: Duration, action: @Sendable @escaping (T) async -> Void) -> some View {
self
.task {
for await query in channel.debounce(for: duration) {
await action(query)
}
}
.task(id: query) {
await channel.send(query)
}
}
func debounce<T: Sendable & Equatable>(_ query: T, using channel: AsyncChannel<T>, for duration: Duration, action: @Sendable @escaping () async -> Void) -> some View {
self
.task {
for await _ in channel.debounce(for: duration) {
await action()
}
}
.task(id: query) {
await channel.send(query)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment