Last active
September 2, 2025 08:27
-
-
Save LucasAbijmil/2d93acfa2edbba9959aa3efb55145010 to your computer and use it in GitHub Desktop.
Debounce in SwiftUI using async/await, AsyncChannel & Observable macro
This file contains hidden or 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
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