DebouncedOnChange
DebouncedOnChange copied to clipboard
how to cancel the debounce?
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.
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.
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?
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.
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.
Available in 2.0.0