Post

Replies

Boosts

Views

Activity

Reply to How to Debounce and Throttle Using @Observable
@Dionysus-Design  If you just want to debounce, you can use this code : public actor Debouncer { private let duration: Duration private var isPending = false public init(duration: Duration) { self.duration = duration } public func sleep() async -> Bool { if isPending { return false } isPending = true try? await Task.sleep(for: duration) isPending = false return true } } Put this code in your Observable: private let debouncer = Debouncer(duration: .seconds(0.5)) func checkEmailValidity() async { guard await debouncer.sleep() else { return } ... do your debounced stuff here ... } And somewhere on your SwiftUI View for example: .onChange(of: viewModel.email) { Task { await viewModel.checkEmailValidity() } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Dec ’23