DebouncedOnChange icon indicating copy to clipboard operation
DebouncedOnChange copied to clipboard

how to cancel the debounce?

Open mesqueeb opened this issue 1 year ago • 1 comments

mesqueeb avatar Mar 14 '24 02:03 mesqueeb

As you've already figured out that is currently not possible.

May I ask you what is your use case, where you want to cancel debounce? That way we can figure out an API that'll work for most use cases. Or we'll add task parameter like in your suggested pull request.

Tunous avatar Mar 14 '24 10:03 Tunous

Hello @Tunous! Sorry I missed your notifications and this slept through the cracks.

The use case is simple:

  • execute a search API call on every keystroke. However, we debounce this to about 500ms.
  • if the user hits ENTER it should cancel the debounce Task and immediately make API call
  • if the user hits ESC it should cancel the debounce Task and never execute it

I'm currently using my own fork, but interested in seeing your solution to a use case like this.

mesqueeb avatar Jul 13 '24 07:07 mesqueeb

Hey @mesqueeb, thanks for the use case. Here is my proposition.

An optional debouncer parameter on the onChange method. It would provide a function to cancel ongoing debounce at any time. For example:

@State private var debouncer = Debouncer()

var body: some View {
    SomeView()
        .onChange(of: query, debounceTime: .microseconds(500), debouncer: debouncer) {
            callApi()
        }
        .onKeyPress(.return) {
            debouncer.cancel()
            callApi()
            return .handled
        }
        .onKeyPress(.escape) {
            debouncer.cancel()
            return .handled
        }
}

What do you think?

Tunous avatar Jul 13 '24 10:07 Tunous

Yes this API makes a lot of sense to me. My previous PR wasn't even a valid solution I realized btw. 😅 But this should work.

mesqueeb avatar Jul 13 '24 10:07 mesqueeb

I've submitted #4 with implementation. Try it out by pointing the package to that branch and let me know if this addresses your issue or if some changes are necessary.

Tunous avatar Jul 13 '24 14:07 Tunous

Available in 2.0.0

Tunous avatar Jul 13 '24 15:07 Tunous